Scanner类
1.Scanner类是什么
通过定义一个Scanner类的对象,我们可以获取用户在键盘上的输入,实现用户和程序的交互
2.如何使用
2.1 next和hasnext
import java.util.Scanner;
public class Demo1_scanner {
public static void main(String[] args) {
//创建scanner类用来接受键盘输入
Scanner scanner =new Scanner(System.in);
System.out.println("请输入字符串1:");//hello world
if(scanner.hasNext()){
String str=scanner.next();//使用next接受字符
System.out.println("你的输入1:"+str);//hello
}
//io流类,使用完需要释放资源
scanner.close();
}
}
2.2 nextLine和hasnextLine
import java.util.Scanner;
public class Demo2_scanner {
public static void main(String[] args) {
//创建scanner类用来接受键盘输入
Scanner scanner = new Scanner(System.in);
System.out.println("请输入字符串2:");//hello world
if(scanner.hasNextLine()){
String str2 = scanner.nextLine();//使用nextLine接受字符
System.out.println("你的输入2:" + str2);//hello world
}
//io流类,使用完需要释放资源
scanner.close();
}
}
2.3 next和nextLine的区别
从2.1和2.2可以看到,使用next和nextLine是又区别的,同样输入的是hello world ,使用next获取的是hello,儿nextLine就是hello world,下面列出两者的区别:
(1)next(),next会过滤掉第一个有效字符之前的所有无效字符(包括空格、回车、tab等),等获取到有效字符之后,又会将有效字符之后遇到的第一个无效字符当作结束标志。因此next获取到的字符是不会有空格的,所以hello world中,hello是第一个有效字符,之后的空格就被当成了结束标志。
(2)nextLine()有扫描一整行的意思,结束标识只有代表换行的回车键,所以使用nextLine时,回车键之前的所有字符都是有效字符
2.4next和hasNext
(1)hasNext():会返回bool值,用来判断缓冲区是否还有字符,有的话就返回true
(2)next():返回的是键盘输入的值
(3)next和hasNext都可以用来输入,如果没有输入,就会阻塞程序
public class Demo2_scanner {
public static void main(String[] args) {
//创建scanner类用来接受键盘输入
Scanner scanner = new Scanner(System.in);
if(scanner.hasNextLine()){
System.out.println("请输入字符串2:");//hello world
String str2 = scanner.nextLine();//使用nextLine接受字符
System.out.println("你的输入2:" + str2);//hello world
}
//io流类,使用完需要释放资源
scanner.close();
}
}