2013-12-18 46 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,並通過方法簽名它給出提示,它會調用者爲您返回新的輸入值