Java - 如何结束一个 while 函数的进程



我需要一个程序,要求用户引入最多10个名字(最后,用户可以键入"fim"[葡萄牙语结尾](。

我目前的问题是如果用户达到 10 个名称,如何终止程序。

这是我的主要功能:

public static void main(String[] args) {
    Scanner keyboard = new Scanner (System.in);
    System.out.println("Introduza até 10 nomes completos com até 120 caracteres e pelo menos dois nomes com pelo menos 4 caracteres: ");
    String nome = keyboard.next();
    for(int i = 0; i < 10; i++) {
        while(!nome.equalsIgnoreCase("fim") && i<10) {
            nome = keyboard.next();
        }
    }
    keyboard.close();
}

您正在按原样运行while的无限循环。您想将其更改为if语句,并仅要求fim,如果发生这种情况,请致电break;

所以它应该以:

for(int i = 0; i < 10; i++) { //This will run 10 times
    nome = keyboard.next();
    if(nome.equalsIgnoreCase("fim")) { //This will verify if last input was "fim"
        break; //This breaks the for-loop
    }
}

或者,如果您真的想在for循环中使用while循环(不推荐(,则需要在其中增加i

for(int i = 0; i < 10; i++) {
    while(!nome.equalsIgnoreCase("fim") && i<10) {
        nome = keyboard.next();
        i++;
    }
}

我不是break的忠实粉丝,所以除了 Frakcool 的出色答案之外,您还可以使用 do-while 循环:

String nome;
int i = 0;
do {
    nome = keyboard.next();
    i++;
}
while(!nome.equalsIgnoreCase("fim") && i<10);

同样现在,您正在覆盖所有以前输入的名称。因此,您要么必须直接在循环中处理它们,要么将它们收集在某种容器中,例如列表。我会这样重写循环:

String nome;
int i = 0;
while(i<10 && !(nome = keyboard.next()).equalsIgnoreCase("fim")) {
    i++;
    // Either handle nome here directly, or add it to a list for later handling.
}

您可能想尝试一下这段代码(我在注释中对正确的行进行了一些解释(:

public static void main(String[] args) {
    Scanner keyboard = new Scanner (System.in);
    System.out.println("Introduza até 10 nomes completos com até 120 caracteres e pelo menos dois nomes com pelo menos 4 caracteres: ");
    String nome = keyboard.next();
    int i = 0; // Here I instroduce a counter, to increment it after each input given
    while(!nome.equalsIgnoreCase("fim") && i!=10) { // stop performing while-loop when nome is equal to "fim"
                                                    // or if i==10 (if any of these conditions is false, entire condition is false)
        nome = keyboard.nextLine();
        i++; // increment counter after input
    }
    keyboard.close();
    System.out.println("End of input"); // Just to confirm that you exited while-loop
}

相关内容

  • 没有找到相关文章

最新更新