-2

大家好,我试图用这段代码退出一个循环,但在它结束之前它仍然会打印出我不想要的行:

do {
        System.out.println("Would you like to change one of the numbers    (y/n)?");
        choice = kb.next().charAt(0);
        System.out.println("Please enter the index of the number you want to change:");
        indexChange = kb.nextInt();
        System.out.println("Please enter the number you want to change:");
        changedIndex = kb.nextInt();
        elements[indexChange - 1] = changedIndex;
        for (int i = 0; i < elements.length; i++)
            System.out.println(index[i] + elements[i]);

    } while (choice != 'n');

这两行在循环结束之前仍然打印出来:“请输入您要更改的号码:”&“请输入您要更改的号码:”。你们中的任何人都可以帮助解决这个错误吗?

4

4 回答 4

3

您需要break在循环中使用 a 。在这种情况下,无需choice在循环的每次迭代的开始或结束时检查,因此您可以使用while (true)to 循环直到break达到。

while (true) {
        System.out.println("Would you like to change one of the numbers    (y/n)?");
        choice = kb.next().charAt(0);
        if (choice == 'n')
            break;
        System.out.println("Please enter the index of the number you want to change:");
        indexChange = kb.nextInt();
        System.out.println("Please enter the number you want to change:");
        changedIndex = kb.nextInt();
        elements[indexChange - 1] = changedIndex;
        for (int i = 0; i < elements.length; i++)
            System.out.println(index[i] + elements[i]);

    }

不过要小心。很容易不小心写出无限循环!

于 2013-02-18T22:41:34.520 回答
1

您需要在处理剩余输入之前检查退出条件...

do {
    System.out.println("Would you like to change one of the numbers    (y/n)?");
    choice = kb.next().charAt(0);
    if (choice != 'n' && choice != 'N') {
        System.out.println("Please enter the index of the number you want to change:");
        indexChange = kb.nextInt();
        System.out.println("Please enter the number you want to change:");
        changedIndex = kb.nextInt();
        elements[indexChange - 1] = changedIndex;
        for (int i = 0; i < elements.length; i++) {
            System.out.println(index[i] + elements[i]);
        }
    }

} while (choice != 'n' && choice != 'N');

您还应该检查大写字符...

于 2013-02-18T22:41:09.327 回答
0

这个检查

 while (choice != 'n');

do 循环的每次迭代仅发生一次。因此,在您的循环中,您询问是否要更改其中一个数字,然后询问其他问题,然后检查他们为第一个问题输入的值。

您可以在获得他们的选择后使用关键字“break”来跳出循环。例如。

if (choice == 'n') 
{
   break;
}
于 2013-02-18T22:43:03.470 回答
0

尝试...

while(!'n'.equals(choice.toLowerCase())){...
于 2013-02-18T22:51:15.353 回答