我尝试使用 while 循环向我的程序添加一个计数器,但尚未使其正常工作。有人可以告诉我哪里出错了,我让它工作了一点,但如果我输入正确的值,“错误”文本仍然会出现,它不会跳出循环。
public class Username {
public static void main (String[]args) {
Scanner kb = new Scanner (System.in);
String [] name = {"barry", "matty", "olly","joey"};
int j = 0;
while (j < 3) {
System.out.println("Enter your name");
String name1 = kb.nextLine();
boolean b = true;
for (int i = 0; i < name.length; i++) {
if (name[i].equals(name1)) {
System.out.println("you are verified you may use the lift");
break; // To stop loop checking names
}
}
System.out.println("wrong");
j++;
}
}
}
最佳答案
外部循环,while
,用于允许的尝试。您需要一种额外的方法来指示它中断,因为 break
语句只能从 for
循环中中断。其中一种方法是使用 boolean
指示符:
boolean found = false;
int attempts = 0;
while (!found && attempts < 3) {
System.out.println("Enter your name");
String name1 = kb.nextLine();
for (int i = 0; i < name.length; i++) {
if (name[i].equals(name1)) {
System.out.println("you are verified you may use the lift");
found = true;
break;// to stop loop checking names
}
}
if (!found) {
System.out.println("wrong");
}
++attempts;
}
关于java - 修复包含计数器的 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22735228/