Java Scanner 输入困境。自动输入,无需用户输入
非常感谢您的回复,我可能会坚持只添加额外的 input.nextLine() 语句来捕获任何“剩余”
因此,在这段代码中我输入 2,一旦它进入 if 语句跳过“sCreateLogin = input.nextLine();”并继续进行下一个输入。可能是因为扫描仪中存在一些挥之不去的东西,但我无法弄清楚它为什么会这样做以及如何准确地修复它。
如果我执行 input.next() 它会停止,但它还不够好,因为如果您不小心添加空格,它也会跳过下一个输入。我知道我可以解析它等,但我仍然对此感到困惑。
Scanner input = new Scanner(System.in);
System.out.println("(1) Login");
System.out.println("(2) Create Account");
int iAccountOption = input.nextInt();
if(iAccountOption==2)
{
System.out.println("Input desired login: ");
String sCreateLogin = input.nextLine();
System.out.println("Input desired password: ");
String sCreatePassword = input.nextLine();
}
Thanks a lot for responses, I will probably stick to just adding extra input.nextLine() statements to catch any "leftovers"
So in this code I input 2, and once it goes to the if statement it skips the "sCreateLogin = input.nextLine();" and proceeds to the next input. Probably because there is something lingering in the Scanner yet I cannot figure out why it does it and how exactly to fix it.
If I do input.next() it stops, but it just isn't good enough because if you accidentally add a space it will also skip the next input. I know I could parse it etc., but I'm still confused with this.
Scanner input = new Scanner(System.in);
System.out.println("(1) Login");
System.out.println("(2) Create Account");
int iAccountOption = input.nextInt();
if(iAccountOption==2)
{
System.out.println("Input desired login: ");
String sCreateLogin = input.nextLine();
System.out.println("Input desired password: ");
String sCreatePassword = input.nextLine();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
问题可能是未处理的行结束标记。要解决此问题,请在 input.nextInt(); 之后添加额外的 input.nextLine() 来吞掉行尾标记:
The problem is likely end of line tokens that are not being dealt with. To fix this, after input.nextInt(); add an extra input.nextLine() to swallow the end of line tokens:
尝试为字符串使用不同的 Scanner 对象。
Try having a different Scanner object for String.
我建议您使用以下两种方式之一:
1.使用BufferedReader类
1a.使用BufferedReader类并用InputStreamReader类包装它。
1b.现在由于readLine方法抛出了IOException,所以你需要捕获它。所以整个代码看起来像这样。
2.如果您使用的是Java SE6或更高版本,那么您可以使用Console类
I will suggest you to use either of these two ways :
1. Using BufferedReader class
1a.Use BufferedReader Class and Wrap it with the InputStreamReader Class.
1b.Now since the readLine method throw an IOException, so you need to catch it. so the whole code will look like this.
2.if you are using the Java SE6 or higher then you can make use of Console class
它正在跳过 sCreateLogin,因为 Scanner.nextLine() 已经有一个值“\r \n”。
所以我将所有扫描仪更改为 nextLine()。结果很好,但也许这不是最好的主意。
请记住在 new Integer(scanner.nextLine()) 上使用 try catch
It was skipping sCreateLogin because scanner.nextLine() already had a value "\r \n".
So I changed all scanners to nextLine(). It worked out fine, but maybe it won't be the best idea.
Remember to use try catch on new Integer(scanner.nextLine())