我写了这段代码:
while (choice > 2 && count <= 2) {
System.out.println("The number you have typed is invalid. Please try again.");
choice = s.nextInt();
count++;
}
if (choice == 1 && count <= 2) {
System.out.println("You have chosen teacher's information.");
t.information();
} else if (choice == 2 && count <= 2) {
System.out.println("You have chosen student's information.");
st.info();
} else {
System.out.println("You have been blocked.");
}
按照我的意图,如果我尝试超过2次,我将被阻止,但是,在另一个项目中:
while (!rusern.equalsIgnoreCase(username) || !rpass.equals(password) && attempts <= 2) {
System.out.println("Login error. Your username is: " + rusern.equalsIgnoreCase(username) + " ,and password is: " + rpass.equals(password) + "\nPlease try again.");
System.out.println("Please enter your username:");
rusern = s.nextLine();
System.out.println("Enter your password:");
rpass = s.nextLine();
attempts++;
//here i have to use break;
}
if (rusern.equalsIgnoreCase(username) && rpass.equals(password) && attempts <= 2) {
System.out.println("You have succesfully logged in! Please continue: ");
} else {
System.out.println("You have been blocked.");
}
我必须使用休息;在while循环中,我在评论中提到过,因为除非我使用了休息,如果我没有正确回答,它会一遍又一遍地显示问题而不停止,当我最终回答正确时,它会阻止我。所以我的问题是,如果没有第一个项目中的休息,为什么它不会起作用? 两个变量,'尝试'和'计数'并初始化相同,= 0。
答案 0 :(得分:2)
a || b && c
表示a || (b && c)
,而我认为您的意图是(a || b) && c
。
请参阅Java operator precedence table:||
和&&
没有相同的优先权。
所以你的循环应该是:
while ((!rusern.equalsIgnoreCase(username) || !rpass.equals(password)) && attempts <= 2) {