java - 我的 boolean 值总是正确的

标签 java if-statement boolean

在下面的代码中,我希望比较文本文件的一部分。 但是,由于某种原因,无论用户输入什么值都会出现 正确。

我正在尝试比较该值,而不用担心它的大小写或任何 前导或尾随空格。

// 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();

最佳答案

试试这个。

// 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");
}

关于java - 我的 boolean 值总是正确的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19017734/

相关文章:

java - 对象/关系映射

java - 使用 JNA 获取 GetForegroundWindow();

java - JTable 呈现已删除的 JButton 而不是新的 JButton

c - else 语句导致输出不正确

python - else、elif、if Python 中的问题

actionscript - 在 Actionscript 中测试 boolean 值是否为空

java - Java 的 mysql 执行时间

arrays - ARRAY公式EXCEL中的多条件IF语句

ruby - 在 Ruby 中将空字符串转换为 nil

python - 为什么 'and' 和 'or' 在 Python 中返回操作数?