Scanner 中next 和nextLine的使用

今天再写一段代码时发现一个奇怪现象,代码如下:

while(loop) {
    
    
            System.out.print("add:添加一个数\n" +
                    "get:取出一个数\n" +
                    "dispaly:展示所有数\n" +
                    "exit:推出\n" +
                    "请输入:");
            String str = sc.nextLine();
            System.out.println("str = "+str);
            switch (str) {
    
    
                case "add":
                    System.out.println("输入一个要添加的数:");
                    int value = sc.nextInt();
                    //sc.next();
                    queue.add(value);
                    break;
                case "get":
                    try {
    
    
                        System.out.println(queue.get());
                    } catch (Exception e){
    
    
                        e.printStackTrace();
                    }
                    break;
                case "display":
                    queue.display();
                    break;
                case "exit" :
                    sc.close();
                    loop = false;
                    break;
                default:
                    System.out.println("输入有误!");
                    break;
            }

我发现每次输入add后他都会输出两个循环,但是其他的指令就不会出现这种情况,后来得知把nextLine换成next就行了。
于是我就去试了一下这两个函数。

public static void main(String[] args) {
    
    
        Scanner sc = new Scanner(System.in);
        String a = sc.next();
        String b = sc.nextLine();
        System.out.println("a = "+ a);
        System.out.println("b = "+ b);
    }

在这里插入图片描述
我们只输入123然后按回车,发现程序自动结束了,但我们明明想要输入两个数,我个人认为是next函数会把回车滞留在缓冲区,以至于下一个nextLine函数直接就读取回车了。

public static void main(String[] args) {
    
    
        Scanner sc = new Scanner(System.in);
        String a = sc.nextLine();
        String b = sc.nextLine();
        System.out.println("a = "+ a);
        System.out.println("b = "+ b);
    }

然后我们把代码稍作修改,结果如下:
在这里插入图片描述
这就是我们想要的结果了,也就证明nextLine函数不会把回车符滞留在缓冲区。
我也试过nextInt和nextDouble.都和next一样。
所以一定要慎重使用nextLine哦。

猜你喜欢

转载自blog.csdn.net/m0_45972156/article/details/120921388
今日推荐