Scanner对象
用来实现程序和人的交互,Java.util.Scanner是java5 的新特征,我们 可以通过Scanner 类来获取用户的输入。
基本语法:
Scanner s = new Scanner(System.in);
通过Scanner 类的 next() 与 nextLine() 方法获取输入的字符串,在读取前我们一般需要 使用 hasNext() “还是否有下一个,搭配 if 语句” 与 hasNextLine() “还是否有下一行,搭配 if 语句” 判断是否还有输入的数据。
import java.util.Scanner;、//导入Scanner包,自动
public class Demo01 {
public static void main(String[] args) {
//创建一个扫描器对象,用于接收键盘数据
Scanner s =new Scanner(System.in);
System.out.println("使用next方式接收:");
//判断用户有没有输入字符串
if (s.hasNext()==true){
//使用next方式接收
String str =s.next();//程序会等待用户输入完毕
System.out.println("输出的内容为:"+str);
}
//凡是属于IO流的类如果不关闭会一直占用资源.要养成好习惯用完就关掉
s.close();
}
}
next():
有空格就会断掉
-
1.一定要读取到有效字符后才可以结束输入
-
2.对输入有效字符之前遇到的空白,next()方法会自动将其去掉。
-
3.只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符。
-
4.next()不能得到带有空格的字符串。
if (s.hasNext()==true){
//使用next方式接收
String str =s.next();//程序会等待用户输入完毕
System.out.println(“输出的内容为:”+str);
nextLine():
有回车会断掉
-
1.以Enter为结束符,也就是说nextLine()方法返回的是输入回车之前的所有字符。
扫描二维码关注公众号,回复: 12557463 查看本文章 -
2.可以获得空白。
if(scanner.hasNextLine()){ String str= scanner.nextLine(); //等待用户去输入 System.out.println("输出的内容为:"+str);
nextInt():
整数型
以空格结束
nextflout():
浮点型
以空格结束
例:
import java.util.Scanner;
public class Demo04 {
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();
}
}
应用题:
我们可以输入多个数字,并求其总和与平均数,每输入一个数字用回车确认,通过输入非数字来结束输入并输出执行结果:
import java.util.Scanner;
public class Demo05 {
public static void main(String[] args) {
//我们可以输入多个数字,并求其总和与平均数,每输入一个数字用回车确认,通过输入非数字来结束输入并输出执行结果:
Scanner scanner =new Scanner(System.in);
double sum = 0;
//计算输入了多少个数字
int m= 0;
//通过循环判断是否还有输入,并在里面对每一次进行求和和统计
while (scanner.hasNextDouble()){
double x = scanner.nextDouble();
m=m+1;
sum =sum + x;
System.out.println("你输入了第"+m+"个数据,然后当前结果sum="+sum);
}
System.out.println(m+"个数的和为"+sum);
System.out.println(m+"个数的平均值是"+(sum/m));
scanner.close();
}
}