Java扫描仪输入困境.自动输入,无需用户输入 [英] Java Scanner input dilemma. Automatically inputs without allowing user to type

查看:79
本文介绍了Java扫描仪输入困境.自动输入,无需用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

非常感谢您的回应,我可能会坚持只添加额外的input.nextLine()语句以捕获任何剩菜"

因此,在这段代码中,我输入2,然后转到if语句,则跳过"sCreateLogin = input.nextLine();".并进入下一个输入.可能是因为扫描仪中有一些残留物,但我无法弄清楚为什么会这样做以及如何正确修复它.

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.

如果我输入input.next(),它会停止,但还不够好,因为如果您不小心添加了空格,它也会跳过下一个输入.我知道我可以解析它,等等,但是我对此仍然感到困惑.

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();
}

推荐答案

问题很可能是未处理的行尾标记.要解决此问题,请在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:

int iAccountOption = input.nextInt();
input.nextLine();
if (iAccountOption == 2) {
   .....

这篇关于Java扫描仪输入困境.自动输入,无需用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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