2013-09-26 103 views
0

在我的下面一段代碼中,我期待比較一段文本文件。 但是,由於某種原因,無論用戶輸入的值是什麼, 都正確。我的布爾總是出現正確

我試圖比較這個值,而不用擔心它的情況或任何 前導空白或尾隨空白。

// Display the question to the user 
System.out.println("Question: " + myList.get(random1)); 

// Accept user input 
System.out.print("Please type your answer: "); 

// Store the user answer in a variable but lowercase 
answer = scanner.nextLine().toLowerCase(); 
System.out.println(); 

// Display the officially correct answer from the arraylist 
System.out.println("Answer: " + myList.get(random1 +1)); 

// if the user answer matches the official answer, tell them they're 
// correct and award points 
// else tell them they suck LOL 
if(myList.get(random1 + 1).contains(answer) == false) { 
    System.out.println("Correct!"); 
    totalScore = totalScore + awardedPoints; 
    System.out.println("You won " + awardedPoints); 
} 
else { 
    System.out.println("You suckkkkkkk"); 
} 

// Display total accumulated points 
System.out.println("Your total points are: " + totalScore); 

// Wait for user to hit any key before displaying the next question 
System.out.print("Hit Enter"); 
scanner.nextLine(); 
+5

的建議:不要使用'myList.get(random1 +1)。載有(回答)== FALSE',使用'myList.get(random1 +1)。載有(回答)' –

+2

如何!是myList定義的?什麼是隨機1? – sashkello

+2

如果官方答覆不包含輸入的答案,那被認爲是正確的? –

回答

2

試試這個。

// Display the officially correct answer from the arraylist 
String correctAnswer = myList.get(random1 +1); 
System.out.println("Answer: " + correctAnswer); // Instead use a variable 

// if the user answer matches the official answer, tell them they're 
// correct and award points 
// else tell them they suck LOL 
if(correctAnswer.equalIgnoreCase(answer)) { // efficient than contains() method 
    System.out.println("Correct!"); 
    totalScore = totalScore + awardedPoints; 
    System.out.println("You won " + awardedPoints); 
} 
else { 
    System.out.println("You suckkkkkkk"); 
}