package com.study.scanner;
import java.util.Scanner;
public class Demo03 {
public static void main(String[] args) {
int i = 0;
float f = 0.0f;
System.out.println("请输入整数:");
Scanner scanner = new Scanner(System.in);
if (scanner.hasNextInt()){
i = scanner.nextInt();
System.out.println("您输入的整数数字为:"+i);
}
else {
System.out.println("您输入的不是整数");
}
System.out.println("请输入小数:");
if (scanner.hasNextFloat()){
f = scanner.nextFloat();
System.out.println("您输入的小数数字为:"+f);
}
else {
System.out.println("您输入的不是小数");
}
scanner.close();
}
}
package com.study.scanner;
import java.util.Scanner;
public class Demo04 {
public static void main(String[] args) {
// 我们可以输入多个数字,并求总和与平均数,每输入一个数字回车确认,通过输入非数字来结束输入并输出执行结果
// 和
double sum = 0;
// 计算输入了多少个数字
int m = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("请输入数字:");
while (scanner.hasNextDouble()){
double x = scanner.nextDouble();
sum = sum + x;
m++;
System.out.println("您输入的第" + m +"次数字,和为:" + sum);
}
System.out.println("总和为:" + sum);
System.out.println("平均值为:" + sum/m);
scanner.close();
}
}
|