【问题标题】:My boolean always comes up correct [closed]我的布尔值总是正确的[关闭]
【发布时间】:2013-10-01 19:14:11
【问题描述】:

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

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

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

【问题讨论】:

  • 建议:不要使用myList.get(random1 +1).contains(answer) == false,使用!myList.get(random1 +1).contains(answer)
  • myList 是如何定义的?什么是 random1?
  • 如果官方答案不包含输入的答案,是否认为是正确的?
  • @ScottHunter 哦,好眼睛!
  • 这个问题似乎跑题了,因为它太本地化了;问题中的代码检查条件是否为假,而不是检查条件是否为真。问题和答案不太可能对未来的访问者有用。

标签: java if-statement boolean


【解决方案1】:

试试这个。

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

【讨论】:

    猜你喜欢
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 2020-07-05
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多