Scanner进阶用法
判断是否为整数,浮点数
package charpter2;
import java.util.Scanner;
public class Scanner3 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
//从键盘接收数据
int i=0;
float f=0.0f;
System.out.println("请输入整数:");
if(s.hasNextInt()){
i = s.nextInt();
System.out.println("整数数据:"+i);
}else{
System.out.println("不是整数");
}
System.out.println("请输入小数:");
if(s.hasNextFloat()){
f = s.nextFloat();
System.out.println("小数数据:"+f);
}else{
System.out.println("不是小数");
}
s.close();
}
}
一个小的应用:
package charpter2;
import java.util.Scanner;
public class Scanner4 {
//输入多个数字,并求其和与平均数,每输入一个数字用回车确认,通过输入非数字结束输入并输出执行结果;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
//和
double sum = 0;
//输入个数
int m = 0;
System.out.println("请输入:");
while(s.hasNextDouble()){
sum+=s.nextDouble();
m++;
}
System.out.println("和:"+sum);
System.out.println("平均数:"+sum/m);
s.close();
}
}
标签:进阶,Scanner,sum,System,用法,println,输入,out From: https://www.cnblogs.com/ssl-study/p/16727981.htmlhttps://www.bilibili.com/video/BV12J41137hu?p=34&vd_source=b1c9346178fc41766e00c3d88901f1cf