2014-05-15 34 views
-1

我想做一个测验类型的游戏,并且由于某种原因,当我在它下面添加if语句时,会执行两次ask方法。在它返回之前,你会问这个问题两次,不管它是否正确。Java如果语句导致方法执行两次

,询问问题
import java.util.Scanner; 

public class QuizGame 
{ 
private int correct; 
private int wrong; 
private Scanner inputScan; 
private Quiz customQuiz; 

public QuizGame() 
{ 
    correct=0; 
    wrong=0; 
    inputScan = new Scanner(System.in); 
} 

private void startQuiz() 
{ 
     System.out.println("Use custom upper limit? (y/n) "); 
     String custom = inputScan.next(); 

     if(custom.equalsIgnoreCase("y")) 
     { 
      System.out.println("What do you want to be your upper limit?"); 
      int limit = inputScan.nextInt(); 
      customQuiz = new Quiz(limit); 
      customQuiz.ask(); 

      if(customQuiz.ask()) 
      { 
       correct +=1; 
       System.out.println("Correct!"); 
      } 
      else 
      { 
       wrong+=1; 
       System.out.println("Wrong!"); 
      } 
     } 
    } 

    public static void main(String[] args) 
    { 
     QuizGame quiz1 = new QuizGame(); 
     quiz1.startQuiz(); 
    } 
} 

其他类:

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

public class Quiz 
{ 
    private Random rGen; 
    private int num1; 
    private int num2; 
    private Scanner getInput; 
    private int answer; 

    public Quiz(int n1) 
    { 
     rGen = new Random(); 
     num1 = rGen.nextInt(n1); 
     num2 = rGen.nextInt(n1); 
     getInput = new Scanner(System.in); 

    } 

    public boolean ask() 
    { 
     int answer = num1 * num2; 
     System.out.println("What is " + num1 + " x " + num2); 
     int userAnswer = getInput.nextInt(); 

     return answer == userAnswer; 
    } 
} 

我孤立的问题,它肯定似乎是if语句:if(customGame.ask()) {}在驱动程序类,但我不明白为什么。这不像if(customGame.ask())再次调用ask方法,它只是测试它是否返回true?我也尝试过,只是if(customGame.ask() == true)仍然没有。

+1

'这不像是(customGame.ask())调用ask方法,是的...那就是精确只是它做了什么。你可以删除原来的调用,或者将它的值存储在变量中,然后在你的if语句中测试变量。 – pinkfloydx33

+0

对不起,我想我误解了这种情况。我认为它只是检查它是真是假 – joe

+1

它调用它并检查结果是真还是假 – pinkfloydx33

回答

6

好了,你在呼唤customQuiz.ask()两次:

customQuiz.ask(); 

if (customQuiz.ask()) 
{ 
    correct += 1; 
    System.out.println ("Correct!"); 
} 

简单地调用它只是一次:

if (customQuiz.ask()) 
{ 
    correct +=1; 
    System.out.println ("Correct!"); 
} 

或(由@RobertHarvey所建议的),你可以把一个方法的结果变量并在以后使用它:

boolean correct = customQuiz.ask(); 
if (correct) 
{ 
    correct += 1; 
    System.out.println ("Correct!"); 
} 
+1

我会把'customQuiz.ask()'的结果;在一个名字有意义的变量中(比如'answerIsCorrect',然后在'if'语句中检查这个变量,但是是这样的: –

+0

@RobertHarvey最初(当我输入答案时)我首先考虑将它放入一个变量中并在该条件中使用该变量),但由于OP不使用结果不止一次,我决定反对它。 – Eran

+0

谢谢伊兰,我想我对条件的理解是离开的,我以为它只是检查如果问()返回true或false – joe