java - 嵌套循环在 Java 程序中不起作用

标签 java for-loop

我正在使用 try-catch 异常处理编写此程序:

    Scanner keyboard = new Scanner(System.in);
    String[] employees = new String[5];
    boolean done1 = false;

    //input and error exception for entering employee names into an array
    for (int i = 0; i < 5; i++)
    {//begin for

        while (!done1)
        {//begin while

            System.out.println("Please enter employee's name: ");
            try
            {//begin try
                employees[i] = keyboard.nextLine();

                if (employees[i].length() == 0)
                    throw new Exception("No name was entered.");

                if (employees[i].length() >= 31)
                    throw new Exception("Name entered contains too many "
                            + "characters");

                for (int check = 0; check < employees[i].length(); check++)
                {//begin for
                    if(Character.isDigit(employees[i].charAt(check)))
                        throw new Exception("Input contains invalid "
                                + "charaters.");
                }//end for

                done1 = true;
            }//end try

            catch (Exception a)
            {//begin catch
                System.out.println("Error: " + a.getMessage());
            }//end catch

        }//end while

    }//end for

当我运行该程序时,它会退出 for 循环,并且只输入 i 的第一个实例,其余的都为空。我怎样才能让程序停留在这个循环中并让它保持错误检查?

最佳答案

您的 done1 变量在第一个循环后保持 true,导致后续 while 语句不进入循环体。

最好完全消除 done1 变量,并使用如下结构:

for (...) {
    while (true) {
        try {
            // get user input
            break;
        } catch (Exception e) {
            // ..
        }
    }
}

关于java - 嵌套循环在 Java 程序中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5358543/

相关文章:

java - 找到不匹配的括号的索引

java - 为什么弃用警告会导致 SBT 中出现编译错误

java - 导致我的程序在 if-else 语句后无法继续运行的字符串数组 - java

java - 2^N 与整数的组合(内核),如何生成它们?

java - Java中for循环之前或内部的初始化

java - 质数不显示正确答案

java - JUnit如何测试多个函数

java - 如何从输入中获取 2 个字母(忽略白色字符并且不能使用数组)

java - 嵌入式 jetty 与 Resteasy 的集成

java - 一个单词中元音的数量