scanner的用法
定义一个scanner
Scanner scanner =new Scanner(system.in)
字符串用法
public class Demo01 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);//创建一个扫描器对象,用于接受键盘数据
System.out.println("请输入数据");
String str = scanner.nextLine();//用于nextLine接收字符串
System.out.println("输出的内容为"+str);
scanner.close();//属于io流的类使用后要关闭
}
}
整数和小数用法
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
float a = 0.0f;
int i = 0;
System.out.println("请输入整数:");
if(scanner.hasNextInt()){
i = scanner.nextInt();
System.out.println("整数数据:"+i);
}else {
System.out.println("输入的不是整数数据");
}
System.out.println("请输入小数:");
if(scanner.hasNextFloat()){
a = scanner.nextFloat();
System.out.println("小数数据:"+a);
}else {
System.out.println("输入的不是小数数据");
}
scanner.close();
}
整数的总和运算
public class Demo03 {标签:scanner,sum,System,Scanner,println,用法,out From: https://www.cnblogs.com/huangjiangfei/p/17920629.html
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//输入多个数字,并求取总和与平均数,通过输入非数字来结束输入并输出执行结果
double sum = 0;
int i = 0;
//通过循环是否还有输入,并在里面对每一次进行求和统计
while (scanner.hasNextDouble()){
double x = scanner.nextDouble();
i = i + 1;
sum = sum + x;
System.out.println("你输入了第"+i+"个数据,然后当前结果sum="+sum);
}
System.out.println(i+"个数的和为"+sum);
System.out.println(i+"个数的平均值为"+(sum/i));
scanner.close();
}
}