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

时间:2013-08-22 22:23:11

标签: java if-statement

所以我在java中创建jeapordy,我不在乎我拼写错了(如果我这样做)但我只有一个问题到目前为止只有一个答案编码,它问问题但只打印出你错了即使答案是对的。

这是问第一个历史问题,答案是乔治,但它打印出答案是错误的。第一个历史问题也值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!");
                    }

                }
            }

        }
}

2 个答案:

答案 0 :(得分:3)

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

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

顺便说一句,完成后请不要忘记关闭Scanners.close()

答案 1 :(得分:1)

int moneyChoice = s.nextInt();只读取整数。它留下了一条待换行。然后String userAnswer = s.nextLine() ;读取一条明显不同于“乔治”的空行。解决方案:在int之后立即读取换行符,并在整个程序中执行。您可能更喜欢创建自己的方法nextIntAndLine()

int moneyChoice= s.nextInt() ;
s.nextLine();