scanner进阶举例
package test.scanner;
import java.util.Scanner;
public class demo04 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int i = 0;
float f = 0.0f;
System.out.println("请输入整数:");
//判断键盘输入是否为整数
if(scanner.hasNextInt()){
//接收键盘输入的整数
i = scanner.nextInt();
System.out.println("输出的内容为:" + i);
}
System.out.println("请输入小数:");
////判断键盘输入是否为小数
if(scanner.hasNextFloat()){
//接收键盘输入的小数
f = scanner.nextFloat();
System.out.println("输出的内容为:" + f);
}
scanner.close();
}
}
package test.scanner;
import java.util.Scanner;
public class demo05 {
public static void main(String[] args) {
//输入多个数字,求其总和与平均数,每输入一个数字回车确认,通过输入非数字结束输入并输出执行结果
Scanner scanner = new Scanner(System.in);
//和
double sum = 0;
//计算输入了多少个数字
int i = 0;
System.out.println("请输入多个整数并回车:");
//通过循环判断是否还有输入,并对每一次输入进行求和和统计
while(scanner.hasNextDouble()){
double x = scanner.nextDouble();
i = i + 1;
sum = sum + x;
System.out.println("输入了第" + i + "个数据,当前结果sum=" + sum);
}
System.out.println(i + "个数的和为" + sum);
System.out.println("输入的所有整数的平均数为:" + (sum / i);
scanner.close();
}
}
标签:进阶,scanner,sum,System,举例,println,输入,out
From: https://www.cnblogs.com/sara0618/p/17099478.html