[英].equals() in java doesn't work?
java中的.equals()
有效嗎? 我的程序有問題,由於某種原因,在while
循環部分它始終處於活動狀態,即使String a = answer[r]
import java.util.Scanner;
public class security {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
String q1[] = {"mother midd name","Father name","your pit name","First school name"};
String a[] = {"Zakia","Mohamed","Dog","Kaliop"};
AskQ(q1,a);
}
public static void AskQ(String q[],String answers[]) {
int r = (int) (Math.random() * q.length) + 1;
for (int i = 0; i < answers.length; i++) {
int c = 1;
System.out.print("please enter your " + q[r] + "?");
String a = sc.nextLine();
do {
c++;
System.out.print("Wrong! try again:");
a = sc.nextLine();
if(c == 2){
System.out.print("only one attempt lift! enter your pass:");
a = sc.nextLine();
c++;
}
if(c == 3){
System.exit(0);
}
c++;
} while (!a.equals(answers[r]));
System.out.println("you are in");
break;
}
}
}
從我所見,您的代碼首先在 for 循環中將 c 設置為 1,然后詢問問題的答案,然后進入 do-while 循環。 在 do-while 循環中,它將 c 增加到 2,然后接收一個問題的另一個答案,然后檢查 c 是否等於 2。由於 c 等於 2,它要求對另一個問題進行回答,然后它增加c 到 3。最后,它檢查 c 是否等於 3(它是)並退出程序。
我建議在 do-while 循環上使用 while 循環,因為在執行任何檢查和錯誤處理之前,您似乎想檢查用戶是否輸入了正確的答案。 如果您使用 do-while 循環,您就在它甚至檢查用戶是否輸入了正確答案之前就進行了錯誤處理。
更重要的是,我建議使用您的第二個 if 語句作為 else-if 語句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.