如何从if语句中返回变量以便在单独的方法中使用?

时间:2015-02-16 22:01:28

标签: java swing methods actionlistener

public int randomNumber()
{
    return (int) (Math.random() * (11 - 1) + 1);
}

public void actionPerformed(ActionEvent e)
{
    if(e.getSource() == question)
    {
        int one = randomNumber();
        int two = randomNumber();
        int three = randomNumber();
        int four = randomNumber();          
        label.setText("Is " + one + "+" + two + " greater than, less than or equal to " + three + "+" + four + "?");
    }

    if(e.getSource() == lessThan)
    {
            if((one+two)<(three+four))
                    label.setText("Correct!");
    }
}

在此代码中,如何保留随机生成的变量:onetwothreefour

我正在为询问用户的问题显示这些变量。然后,我希望能够比较这些变量以检查正确的用户输入答案并显示适当的反馈。

目前,当我编译此代码时,它会出现错误,指出无法找到变量onetwothreefour,这是有道理的,因为他们在一份单独的声明中。如何在actionPerformed方法中重复使用它们?

3 个答案:

答案 0 :(得分:1)

将变量one, two, three,four声明在您拥有的actionPerformed方法可见的更高范围内。例如,它们可能是randomNumber()actionPerformed()组成的类中的实例变量。这样,变量在方法调用之间保持状态,并且通过actionPerformed可见。

之后,您可以通过将该答案存储在实例变量中来存储验证用户是否正确回答的结果(如果您需要在其他地方使用它)。

答案 1 :(得分:0)

你的int,two,three ....的设置应该在你的if语句之前。您的变量仅在您输入if语句时定义,如果您不输入它,则永远不会定义它们。

if(e.getSource() == question)
    {
        int one = randomNumber();
        int two = randomNumber();
        int three = randomNumber();
        int four = randomNumber();          
        label.setText("Is " + one + "+" + two + " greater than, less than or equal to " + three + "+" + four + "?");
    }

应该是

 int one = randomNumber();
 int two = randomNumber();
 int three = randomNumber();
 int four = randomNumber();
 if(e.getSource() == question)
        {          
            label.setText("Is " + one + "+" + two + " greater than, less than or equal to " + three + "+" + four + "?");
        }

答案 2 :(得分:0)

class a{
    private int one,two,three,four;
    public int getOne(){
        return this.one;
    }

public void setOne(int one){
this.one = one;
}
    public int randomNumber()
    {
        return (int) (Math.random() * (11 - 1) + 1);
    }

    public void actionPerformed(ActionEvent e)
    {

        if(e.getSource() == question)
        {
            setOne(randomNumber());
            two = randomNumber();
            three = randomNumber();
            four = randomNumber();          
            label.setText("Is " + one + "+" + two + " greater than, less than or equal to " + three + "+" + four + "?");
        }

        if(e.getSource() == lessThan)
        {
                if((getOne()+two)<(three+four))
                        label.setText("Correct!");
        }
    }
}
}