我试图使用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++;
}
}
}
Run Code Online (Sandbox Code Playgroud)
外部循环,while用于允许的尝试.你需要一种额外的方式来发出信号来断开,因为break你的声明只是从for循环中断开.一种方法是使用booleanidicator:
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;
}
Run Code Online (Sandbox Code Playgroud)