判断并输出整数、小数
package com.sun.scanner;
import java.util.Scanner;
public class Demo04 {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int i;
float f;
System.out.println("请输入整数:");
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();
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/b8ca126a4f5391eb634c4000f76adec3.png)
求平均数
package com.sun.scanner;
import java.util.Scanner;
public class Demo05 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入数据:");
int m=0;
double sum=0;
while (scanner.hasNextDouble()){
double x=scanner.nextDouble();
m=m+1;
sum+=x;
System.out.println("你输入了第"+m+"个数据,当前结果是sum="+sum);
}
System.out.println(m+"个数的和为"+sum);
System.out.println(m+"个数的平均数为"+(sum/m));
scanner.close();
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7103339ecc1cf15e5f614cc6c837f91b.png)