package javaprac;
import java.util.Scanner;
public class Scanner_demo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in); //scan不是closed,会警告
//next()方法获取字符串数据,以空格作为结束标志
if(scan.hasNext()) {
String str1=scan.next();
//next()方法获取数据时,以空格作为结束标记(此空格为读到有效字符之后的空格,倘若空格在其前,该方法会自动忽略掉)
//因此不能得到带空格的字符串
System.out.println("输入的数据为:"+str1);
}
//nextLine()方法获取字符串数据,以回车作为结束标志
if(scan.hasNextLine()) {
String str2=scan.nextLine(); //nextLine()方法获取数据时,以回车作为结束标记(可以获得空格)
System.out.println("输入的数据为:"+str2);
}
//nextInt()方法获取整形数据
if(scan.hasNextInt()) {
int i = scan.nextInt();
System.out.println("输入整数为:"+i);
}else {
System.out.println("输入的不是整数");
}
//nextInt()方法获取整形数据
if(scan.hasNextFloat()) {
float f = scan.nextFloat();
System.out.println("输入浮点数为:"+f);
}else {
System.out.println("输入的不是浮点数");
}
//输入多个数字,求其总和和平均数
double sum = 0;
int n = 0;
while(scan.hasNextDouble()) {
double x = scan.nextDouble();
n = n + 1;
sum = sum + x;
}
System.out.println(n+"个数的和为:"+sum);
System.out.println(n+"个数的均值为:"+sum/n);
scan.close();
}
}
Scanner类,从键盘获取输入
猜你喜欢
转载自blog.csdn.net/qq_42475914/article/details/100755853
今日推荐
周排行