gpt4 book ai didi

java - 不在 if/else 语句中打印我的代码

转载 作者:行者123 更新时间:2023-11-29 03:30:47 24 4
gpt4 key购买 nike

所以我在 java 中创建了 jeapordy,我不在乎我拼错了(如果我拼错了)但我只有一个问题编码,只有一个答案,它提出问题但只打印出你错了即使答案是正确的。

它问的是第一个历史问题,答案是 george,但打印出来的答案是错误的。第一道历史题也是100分,数学部分我还没开始写代码。

如果你能帮助解决我的问题,谢谢!它可能真的很简单,因为我是初学者。

import java.util.Random;
import java.util.Scanner;

public class game {
public static void main (String[] args){
//Utilites
Scanner s = new Scanner(System.in);
Random r = new Random();

//Variables
String[] mathQuestions;
mathQuestions = new String[3];
mathQuestions[0] = ("What is the sum of 2 + 2");
mathQuestions[1] = ("What is 100 * 0");
mathQuestions[2] = ("What is 5 + 5");

String[] historyQuestions;
historyQuestions = new String[3];
historyQuestions[0] = ("What is General Washingtons first name?");
historyQuestions[1] = ("Who won WWII, Japan, or USA?");
historyQuestions[2] = ("How many states are in the USA?");


//Intro
System.out.println("Welome to Jeapordy!");
System.out.println("There are two categories!\nMath and History");
System.out.println("Math History");
System.out.println("100 100");
System.out.println("200 200");
System.out.println("300 300");


System.out.println("Which category would you like?");
String categoryChoice = s.nextLine();
System.out.println("For how much money?");
int moneyChoice = s.nextInt();
if (categoryChoice.equalsIgnoreCase("history")){
if (moneyChoice == 100){
System.out.println(historyQuestions[0]);
String userAnswer = s.nextLine();
s.nextLine();
if (userAnswer.equalsIgnoreCase("george")){
System.out.println("Congratulations! You were right");
}
else{
System.out.println("Ah! Wrong answer!");
}

}
}

}
}

最佳答案

当您调用 nextInt() 时,换行符未被读取,因此后续调用 nextLine() 将返回一个空字符串(因为它读取到该行的末尾)。在读取/丢弃此尾随换行符之前调用一次 newLine():

if (moneyChoice == 100) {
System.out.println(historyQuestions[0]);
s.nextLine(); // <--
String userAnswer = s.nextLine();
System.out.println(userAnswer);
...

顺便说一句,不要忘记在完成后关闭您的Scanner:s.close()

关于java - 不在 if/else 语句中打印我的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18391754/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com