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

How to return variable from within an if statement for use in a separate method?

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 方法中可重复使用?

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

可见

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

你的int one, 2, 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 + "?");
        }
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!");
        }
    }
}
}