我需要一个程序,要求用户输入最多 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++;
}
}
关于Java - 如何结束 while 函数的进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49309770/