简体   繁体   English

java中的.equals()不起作用?

[英].equals() in java doesn't work?

.equals() in java dosent work? java中的.equals()有效吗? There is a problem with my program, for some reason in the while loop part it is always active even if the String a = answer[r]我的程序有问题,由于某种原因,在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;
    }   
}
}

From what I am seeing, your code first sets c equal to 1 in the for-loop, then asks for an answer to a question, then goes into the do-while loop.从我所见,您的代码首先在 for 循环中将 c 设置为 1,然后询问问题的答案,然后进入 do-while 循环。 Inside of the do-while loop it increments c to 2, then takes in another answer to a question, then checks to see if c is equal to 2. Since c is equal to 2 it asks for an aswer to another question then it increments c to 3. Finally, it checks to see if c is equal to 3 (which it is) and exits the program.在 do-while 循环中,它将 c 增加到 2,然后接收一个问题的另一个答案,然后检查 c 是否等于 2。由于 c 等于 2,它要求对另一个问题进行回答,然后它增加c 到 3。最后,它检查 c 是否等于 3(它是)并退出程序。

I suggest using a while loop over a do-while loop since it looks like you want to check to see if the user entered in the correct answer BEFORE you do any checking and error-handling.我建议在 do-while 循环上使用 while 循环,因为在执行任何检查和错误处理之前,您似乎想检查用户是否输入了正确的答案。 If you use a do-while loop, you are doing the error handling before it ever even checks to see if the user entered in the correct answer.如果您使用 do-while 循环,您就在它甚至检查用户是否输入了正确答案之前就进行了错误处理。

More over, i'd suggest using your second if-statement as an else-if statement.更重要的是,我建议使用您的第二个 if 语句作为 else-if 语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM