java循环没有正确结束

时间:2013-02-18 22:37:22

标签: java

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

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');

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

4 个答案:

答案 0 :(得分:3)

您需要在循环中使用break。在这种情况下,无需在循环的每次迭代的开始或结束时检查choice,因此您可以使用while (true)循环直到达到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]);

    }

但要小心这一点。不小心写出无限循环很容易!

答案 1 :(得分: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');

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

答案 2 :(得分:0)

此检查

 while (choice != 'n');

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

你可以使用关键字“break”在获得他们的选择之后突破循环。

if (choice == 'n') 
{
   break;
}

答案 3 :(得分:0)

...试

while(!'n'.equals(choice.toLowerCase())){...