如何在java中访问此变量?

如何在java中访问此变量?,java,Java,我是Java初学者,我来自C。请看以下代码: public class Ampel { public Ampel(boolean r, boolean y, boolean g) { boolean red = r, yellow = y, green = g; } public void GetStand() { System.out.println(red);

我是Java初学者,我来自C。请看以下代码:

public class Ampel {
    public Ampel(boolean r, boolean y, boolean g) {
        boolean red = r,
                yellow = y,
                green = g;
    }
    public void GetStand() {
        System.out.println(red);
        System.out.println(yellow);
        System.out.println(green);
    }
}

我无法访问
GetStand()
中的“红色”或“黄色”和“绿色”。我该怎么办

您当前正在构造函数中声明局部变量。您需要声明实例变量。例如:

public class Ampel {
    private final boolean red;
    private final boolean yellow;
    private final boolean green;

    public Ampel(boolean r, boolean y, boolean g) {
        red = r;
        yellow = y;
        green = g;
    }

    // Name changed to follow Java casing conventions, but it's still odd to have
    // a "get" method which doesn't return anything...
    public void getStand() {
        System.out.println(red);
        System.out.println(yellow);
        System.out.println(green);
    }
}

请注意,等效的C#代码将以完全相同的方式工作。Java和C#之间没有区别。

将布尔定义为类属性,而不是构造函数范围中的变量。

将红色、黄色和绿色定义为实例变量

public class Ampel {
    private boolean red, yellow, green;
    public Ampel(boolean r, boolean y, boolean g) {
        red = r;
        yellow = y;
        green = g;
   }

   public void getStand() { // java convention is to camelCase method names
       System.out.println(red);
       System.out.println(yellow);
       System.out.println(green);
   }
}

在构造函数外声明红色、黄色和蓝色,使它们成为类的成员。嗯,我猜C#有变量作用域。@MikeSamuel我的观点是,这与C#中的问题完全相同。@Mr.Polywhill:这不是语法问题,而是惯例问题。@Mr.Polywhill:我的观点是你的评论不正确:这意味着这是Java中的规则,是语法的一部分。谢谢,错过了comas,那应该变成分号。嗨,乔恩,我现在不能测试这个。但是如果这是C#那么红色、黄色和绿色不应该在C#中声明为
readonly
,而不是
final
?如果我弄错了,请告诉我。@robbmj:是的,但我没有展示C#-我展示的是Java,因为这是OP写的东西。等效的C代码将使用
readonly
而不是
final