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

Java - How to end a process of a while function

我需要一个程序,要求用户介绍最多 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++;
    }
}

你可能想尝试一下这段代码(我在注释中对适当的行做了一些解释):

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
}

我不是 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.
}