简体   繁体   中英

.equals() in java doesn't work?

.equals() in java dosent work? 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]

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. 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.

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. 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.

More over, i'd suggest using your second if-statement as an else-if statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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