2013-12-18 48 views
5

我有一个关于Java中布尔值的问题。比方说,我有一个这样的程序:更改布尔值?

boolean test = false; 
... 
foo(test) 
foo2(test) 

foo(Boolean test){ 
    test = true; 
} 
foo2(Boolean test){ 
    if(test) 
    //Doesn't go in here 
} 

我注意到,在foo2的,布尔测试不会改变,因此不进入if语句。那么我将如何去改变它呢?我查看了布尔值,但是我找不到可以将“测试”从“真”设置为“假”的函数。如果任何人都可以帮助我,那会很棒。

+2

Java按值传递。使变量成为实例变量并修改并检查该变量。 –

+0

@SotiriosDelimanolis是的。但是java.lang.Object(和子类型,即任何非原始类型)的值是引用地址。 –

+0

@ElliottFrisch我看不到_but_在哪里。 –

回答

4

你一个原始的布尔值传递给你的函数,没有“参考”。因此,您只需要在foo方法中隐藏该值。相反,你可能需要使用下列之一 -

的Holder

public static class BooleanHolder { 
    public Boolean value; 
} 

private static void foo(BooleanHolder test) { 
    test.value = true; 
} 

private static void foo2(BooleanHolder test) { 
    if (test.value) 
    System.out.println("In test"); 
    else 
    System.out.println("in else"); 
} 

public static void main(String[] args) { 
    BooleanHolder test = new BooleanHolder(); 
    test.value = false; 
    foo(test); 
    foo2(test); 
} 

,输出 “在测试”。

或者,通过使用

成员变量

private boolean value = false; 

public void foo() { 
    this.value = true; 
} 

public void foo2() { 
    if (this.value) 
    System.out.println("In test"); 
    else 
    System.out.println("in else"); 
} 

public static void main(String[] args) { 
    BooleanQuestion b = new BooleanQuestion(); 
    b.foo(); 
    b.foo2(); 
} 

其中,还输出 “以测试”。

+0

随着持有人的方法,你需要创建一个名为BooleanHolder的新文件,然后因为它是公开的? – user1871869

+0

我用[Nested Class](http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html)编写了它,但你可以(但它不会是一个静态嵌套类) 。 –

1

您将参数命名为与实例变量相同。在这里,参数是被引用的参数,而不是实例变量。这称为“阴影”,其中简单名称test作为参数名称会遮挡实例变量,也称为test

foo中,您将参数test更改为true,而不更改实例变量test。这解释了为什么它没有进入foo2if区块。

要指定该值,请除去foo上的参数,或使用this.test来引用实例变量。

this.test = true; 

if (this.test) 
+0

嗯,用这个方法我得到一个错误,说:错误:非静态变量,这不能从一个stic上下文引用 – user1871869

0

foo方法将test的值更改为true。它看起来像你想要的是为每个函数使用实例变量。

boolean test = false; 
... 
foo(test) 
foo2(test) 

foo(Boolean test){ 
    this.test = true; 
} 
foo2(Boolean test){ 
    if(this.test) 
    //Doesn't go in here 
} 

这样一来,你的方法只是改变了test该方法内的值,但你的公共test参数保持与false值。

1

您需要注意的是:

  1. 在Java中,参数是通过按值。
  2. 布尔值,boolean的包装类型是不可变的。

由于1和2,您无法更改方法中布尔传递的状态。

您主要有2个选择:

选择1:有布尔像一个可变持有人:

class BooleanHolder { 
    public boolean value; // better make getter/setter/ctor for this, just to demonstrate 
} 

所以在你的代码应该是这样的:

void foo(BooleanHolder test) { 
    test.value=true; 
} 

选择2:更合理的选择:从您的方法返回值:

boolean foo(boolean test) { 
    return true; // or you may do something else base on test or other states 
} 

调用者应该使用它想:

boolean value= false; 
value = foo(value); 
foo2(value); 

这种方法,因为它适合与普通Java编码实践更好preferrable,并通过方法签名它给出提示,它会调用者为您返回新的输入值