Scanner进阶使用
1 package Scanner; 2 3 import java.util.Scanner; 4 5 public class Demo02 { 6 public static void main(String[] args) { 7 //从键盘接收数据 8 Scanner scanner = new Scanner(System.in); 9 System.out.println("使用nextLine方式接收:"); 10 11 //判断是否还有输入 12 if (scanner.hasNextLine()){ 13 String str = scanner.nextLine(); 14 System.out.println("输出的内容为:"+ str ); 15 } 16 scanner.close(); 17 } 18 }
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 System.out.println("请输入数据:"); 9 String str = scanner.nextLine(); 10 System.out.println("请输出内容:" + str); 11 scanner.close(); 12 13 } 14 }
1 package Scanner; 2 3 import java.util.Scanner; 4 5 public class Demo04 { 6 public static void main(String[] args) { 7 Scanner scanner = new Scanner(System.in); 8 //从键盘接收数据 9 int i = 0; 10 float j = 0.0f; 11 System.out.println("请输入整数:"); 12 //如果...那么 13 if (scanner.hasNextInt()){ 14 i = scanner.nextInt(); 15 System.out.println("整数数据:"+ i ); 16 }else{ 17 System.out.println("输入的不是整数数据!"); 18 } 19 System.out.println("请输入小数:"); 20 if (scanner.hasNextFloat()){ 21 j = scanner.nextFloat(); 22 System.out.println("小数数据:"+ j ); 23 }else { 24 System.out.println("输入的不是小数数据!"); 25 } 26 scanner.close(); 27 } 28 }
1 package Scanner; 2 3 import java.util.Scanner; 4 5 public class Demo05 { 6 public static void main(String[] args) { 7 //我们可以输入多个数字,并求其总和与平均数 8 //每输入一个数字用回车确认,通过输入非数字来结束输入并输出执行结果; 9 Scanner scanner = new Scanner(System.in);//输入非字符就会结束 10 11 double sum = 0;//和 12 int m = 0;//计算输入了多少个数字 13 14 //通过循环判断是否还有输入,并在里面对每一次进行求和和统计 15 while(scanner.hasNextDouble()){ 16 double x = scanner.nextDouble(); 17 m = m + 1 ; 18 sum = sum + x ; 19 System.out.println("你输入了第"+m+"个数据,当前结果sum="+sum); 20 } 21 System.out.println(m + "个数的和为:"+ sum); 22 System.out.println(m + "个数的平均值为:"+ (sum/m)); 23 24 scanner.close(); 25 } 26 }