Java Scanner为什么我的代码中的nextLine()被跳过? [英] Java Scanner why is nextLine() in my code being skipped?

查看:126
本文介绍了Java Scanner为什么我的代码中的nextLine()被跳过?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    Scanner kb = new Scanner(System.in);
    System.out.println("Inserting L");
    int L = kb.nextInt();   
    System.out.println("Inserting N");
    int N = kb.nextInt();
    System.out.println("Inserting x");
    String x = kb.nextLine();
    System.out.println(x);
    System.out.println("You inputed L,N,x");

为什么没有提示 nextLine()在此代码中?

Why is there no prompt for nextLine() in this code?

推荐答案

使用:

String x = kb.next();

而不是 kb.nextLine()

这是因为 nextInt()只读取数字,而不是数字后面的行尾或任何内容。当你打电话给 nextLine()时,它会读取同一行的剩余部分并且不等待输入。

This is because nextInt() reads just the number, not the end of line or anything after the number. When you call nextLine() it reads the remainder of the same line and does not wait for input.

理想情况下你应该在 nextInt()的代码后面的 kb.nextLine()中调用该行,忽略其余部分。

Ideally you should call kb.nextLine() the line after your code for nextInt() to ignore the rest of the line.

这篇关于Java Scanner为什么我的代码中的nextLine()被跳过?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆