Java if语句导致方法执行两次

时间:2014-05-15 01:34:33

标签: java

我正在尝试制作一个测验类型的游戏,出于某种原因,当我在下面添加if语句时,它会执行两次ask方法。在返回之前,您会被问到两次是否正确。

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 个答案:

答案 0 :(得分: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!");
}