2

我对 Java 非常陌生,但对 VB.NET 有“一点”经验,这要宽容得多。所以请原谅这可能是一个愚蠢的问题,也请原谅我糟糕的 Java 词汇量。这是控制台应用程序的片段:

do
{
    out.println("Please enter the name of your space bug and press <enter> to continue");
    out.println();
    bugOne.setName(keyInput.nextLine());

    out.println("You have entered '" + bugOne.getName() + "'.");
    out.println("Is this correct? (y/n)");

    confirmName = keyInput.findWithinHorizon(".",0).charAt(0);
}
while(confirmName != 'y' && confirmName != 'Y');

在第一次迭代时它很好,输入的名称显示出来。然后它进入确认状态,如果我输入“y”或“Y”,它会很好地进入下一行代码(如您所料)。

但是,如果我键入其他任何内容,当它通过第二次迭代时,它不会暂停键盘输入。在我输入确认名称请求后,控制台窗口中生成的行立即读取

You have entered "".
Is this correct(y/n)?

为什么不暂停键盘输入?(在 VB 控制台应用程序中,您必须指定何时要暂停用户输入,但从我在 Java 中看到的情况来看,您没有或不能……或者您可以吗?)

为什么我通过访问器方法 setName 设置的“名称”变量在第二次迭代中被自动赋值为空?

4

2 回答 2

1

要从控制台读取字符/字符串,您可以执行以下操作(取自此处):

try{
        BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
        String s = bufferRead.readLine();

        System.out.println(s);
    }

并且字符串不能与==and!=运算符进行比较;使用字符串equalsequalsIgnoreCase.

见这里http://www.tutorialspoint.com/java/java_string_equalsignorecase.htm

于 2013-09-13T03:53:20.503 回答
0

那是因为当你这样做

confirmName = keyInput.findWithinHorizon(".",0).charAt(0);

您正在使用模式 ( .) 告诉扫描仪查找下一个字符。但是,一旦用户输入响应,就会出现不止一个字符(即“n”和换行符)。但是 findWithinHorizo​​n 并没有选择那个换行符,所以当它回到

bugOne.setName(keyInput.nextLine());

它会立即拾取留在那里的空的新行。要解决此问题,您只需在调用 findWithinHorizo​​n 之后添加以下代码行:

keyInput.nextLine();

所以它看起来像这样:

confirmName = keyInput.findWithinHorizon(".",0).charAt(0);
keyInput.nextLine();

但实际上,做这样的事情有什么害处?忘记模式匹配,只需将其作为字符串读入即可。

String confirmName;
do
{
    out.println("Please enter the name of your space bug and press <enter> to continue");
    out.println();
    bugOne.setName(keyInput.nextLine());

    out.println("You have entered '" + bugOne.getName() + "'.");
    out.println("Is this correct? (y/n)");

    confirmName = keyInput.nextLine();
}
while(!confirmName.equalsIgnoreCase("y"));
于 2013-09-13T04:06:30.657 回答