点击查看代码
package com.jia.scanner;
import java.util.Scanner;
public class Demo01 {
public static void main(String[] args) {
//创建一个扫描器对象,用于接受键盘数据
Scanner sc = new Scanner(System.in);
System.out.println("使用next方式接受:");
//判断用户有没有输入字符串
if (sc.hasNext()){
//使用next方式接受
String str = sc.next();
System.out.println("输出的内容:" + str);
}
System.out.println("============================================");
System.out.println("使用nextLine:");
if (sc.hasNextLine()){
String str = sc.nextLine();
System.out.println("输出的内容:" + str);
}
//凡是属于IO流的类,如果不关闭会一直占用资源,要养成习惯用完就关掉
sc.close();//为了节省资源
}
}
这段代码,运行后输出的结果是:
会出现跳过用户输入的现象。但是,并不符合我的需求,我希望是在使用nextLine前,可以再次从键盘输入新的内容,再输出新的结果。
接下来,我们可以从输入缓冲区机制和next还有nextLine两种方法的底层处理逻辑进行分析,该现象产生的原因:
package com.jia.scanner;
import java.util.Scanner;
public class Demo01 {
public static void main(String[] args) {
//创建一个扫描器对象,用于接受键盘数据
Scanner sc = new Scanner(System.in);
System.out.println("使用next方式接受:");
//判断用户有没有输入字符串
if (sc.hasNext()){
//使用next方式接受
String str = sc.next();
sc.nextLine();//紧跟着,使用nextLine释放空格,程序才会接着让用户输入
System.out.println("输出的内容:" + str);
}
System.out.println("============================================");
System.out.println("使用nextLine:");
if (sc.hasNextLine()){
String str = sc.nextLine();
System.out.println("输出的内容:" + str);
}
//凡是属于IO流的类,如果不关闭会一直占用资源,要养成习惯用完就关掉
sc.close();//为了节省资源
}
}
符合我的需求!
参与评论
手机查看
返回顶部