dimanche 1 mars 2015

While loop not breaking even though condition is being met Java



I am trying to write a testing program that checks user responses against a database (basically 3 arrays). Here is the relevant code:



while(true) {
int r = randomnumbergenerator.nextInt(length);
String[] split2 = a[r].split(" ");
String lastNameAnswer = "";
while(!lastNameAnswer.equals(split2[1])) {
System.out.println("What is " + split2[0] + "\'s last name?");
lastNameAnswer = reader.next();
}
String hometownAnswer = "";
String hometown = h[r];
while(!hometownAnswer.equals(hometown)) {
System.out.println("What is " + split2[0] + "\'s hometown?");
hometownAnswer = reader.next();
}
String majorAnswer = "";
String major = m[r];
while(!majorAnswer.equals(major)) {
System.out.println("What is " + split2[0] + "\'s major?");
majorAnswer = reader.next();
}
}


So what should happen is that it should choose a name from the database, and ask questions about the name such as the last name, hometown, and major. If the user's answers are wrong, the question should be repeatedly asked. My code works for last name and major, but for some reason hometown is glitching. Here is the output:



What is Ellen's last name?
Guo
What is Ellen's last name?
Gao
What is Ellen's hometown?
asdf
What is Ellen's hometown?
awsefd
What is Ellen's hometown?
Shanghai China
What is Ellen's hometown?
What is Ellen's hometown?
Shaghai China
What is Ellen's hometown?
What is Ellen's hometown?
Shanghai China
What is Ellen's hometown?
What is Ellen's hometown?


As you can see, I can't get past hometown, even though I know my answer is correct. I entered the correct answer yet the question is repeatedly asked and the loop does not break. I changed the order of the questions (used to be last name, major, hometown, now its last name, hometown, major) but this has had no effect. What is going on? Why does this loop not work but the others do?




Aucun commentaire:

Enregistrer un commentaire