scanner
用scanner类获取用户的输入
Scanner s = new Scanner)(System.in);
通过next()和nextline()获取输入字符串
通过hasNext()和hasNextLine()判断是否还有输入的数据
凡是属于IO流的类如果不关闭会一直占用资源,要用完就关掉。
scanner.close();
next():
-
一定读取到有效字符串才可以结束输入
-
对有效字符串之前的空白,next()会自动去掉
-
next()不能得到带有空格的字符串
1 package scanner; 2 3 import java.util.Scanner; 4 5 public class Demo02 { 6 public static void main(String[] args) { 7 Scanner scanner = new Scanner(System.in); 8 System.out.println("用nextline方式接收数据:"); 9 if(scanner.hasNextLine()){ 10 String str = scanner.nextLine(); 11 System.out.println("输出内容为: "+str); 12 13 14 15 } 16 scanner.close(); 17 18 } 19 }
nextline():
-
以enter作为结束符,输入一行数据
-
可以获得空白
1 package scanner; 2 3 import java.util.Scanner; 4 5 public class Demo03 { 6 public static void main(String[] args) { 7 Scanner scanner = new Scanner(System.in); 8 int i=0; 9 float f = 0.0f; 10 System.out.println("请输入整数: "); 11 if(scanner.hasNextInt()){ 12 i = scanner.nextInt(); 13 System.out.println(i); 14 } 15 else{ 16 System.out.println("不是整数"); 17 } 18 System.out.println("请输入小数: "); 19 if(scanner.hasNextFloat()){ 20 f = scanner.nextFloat(); 21 System.out.println(f); 22 } 23 else{ 24 System.out.println("不是小数"); 25 } 26 27 28 29 scanner.close(); 30 } 31 }
练习
求平均数及总和
1 package scanner; 2 3 import java.util.Scanner; 4 5 public class Demo04 { 6 public static void main(String[] args) { 7 //输入多个数字,求总和及其平均数,输入数字用回车确认,通过非数字结束并输入出结果 8 Scanner scanner = new Scanner(System.in); 9 //求和 10 double sum = 0; 11 //计算输入数字 12 int m = 0; 13 14 //循环 15 while(scanner.hasNextDouble()){ 16 double v = scanner.nextDouble(); 17 m = m+1; 18 sum = sum+v; 19 20 } 21 double average = sum/m; 22 System.out.println("总和为:"+sum); 23 System.out.println("平均数为:"+average); 24 25 26 scanner.close(); 27 } 28 }
标签:Scanner,day7,System,用户,println,out,交互,输入,scanner From: https://www.cnblogs.com/GUGUZIZI/p/16742144.html