2013-08-22 40 views
1

所以即时创建jeapordy在Java中,我不在乎,我拼写错了(如果我做了),但我只有一个问题编码到目前为止只有一个答案,并要求问题,但只打印出你是错的,即使答案是正确的。不打印我的代码在if/else语句

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

       } 
      } 

     } 
} 

回答

3

当你调用nextInt(),一个换行符被读出,所以nextLine()的后续调用会返回一个空字符串(因为它读取到行的结尾)。呼叫newLine()一次读前/丢弃这个换行符:

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

顺便说一句,不要忘记关闭Scanner当你完成了它:s.close()

+0

好的,谢谢!它的工作..我把它放在后面,因为我的老师之一告诉我这是一个愚蠢的日食错误的修复,我从来不知道把它放在前面。 – jason

1

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

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