Scanner进阶使用
- Scanner用法总结:
- new Scanner(System.in);
- scanner.hasNextxxxx等待用户输入
- 赋值给相应类型的变量
- 对整型数据以及浮点型数据的输入
package scanner;
import java.util.Scanner;
public class Demo05 {
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);
}else{
System.out.println("您输入的数据不是整数!");
}
System.out.println("请输入小数:");
if(scanner.hasNextFloat()){
f= scanner.nextFloat();
System.out.println("输入的数据是:"+f);
}else{
System.out.println("您输入的数据不是小数!");
}
scanner.close();
}
}
-
例题
package scanner; import java.util.Scanner; //输入多个数字,求其平均值,以非数字为结束标识 public class Demo06 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); double sum=0; int count=0; while(scanner.hasNextDouble()){ count++; sum =sum + scanner.nextDouble(); } scanner.close(); sum=sum/count; System.out.println(sum); } }