dimanche 1 février 2015

if-statement not functioning correctly [duplicate]


This question already has an answer here:




I am seemingly comparing two strings which are the same (as printed by the println()...however the correct statement is not printing.


Prints..."incorrect" even though the two statements are equivalent.


(Please forgive the basic nature of this application, i am learning)


Your assistance would be appreciated.


J



public static void main (String args[]){
Question q = new Question();
Scanner Scanner = new Scanner(System.in);

for(int i = 0; i<4; i++){
int qNum = i + 1;
System.out.println("Question " + qNum + ": " + q.getQuestion(i));
String x = Scanner.next();
System.out.println(x);
System.out.println(q.getAnswer(i).toString());
if (x.toString() == q.getAnswer(i).toString()){
System.out.println("Correct");
}else{
System.out.println("Incorrect");
}
}
Scanner.close();

}


and the question class...



public String questions[] = {"How many wheels does a car have?",
"How many legs does a monkey have?",
"How many ears does an elephant have?",
"Do penguins fly?"};
public String answers[] = {"4", "2", "2", "No"};


public Question(){

}

public String getQuestion(int q){

return questions[q];
}

public String getAnswer(int q){

return answers[q];
}

Aucun commentaire:

Enregistrer un commentaire