簡體   English   中英

如何在方法-Java中更改布爾值?

[英]How do I change the value of a boolean within a method - Java?

我讀過一本書,當您更改方法參數為布爾型或其他基本數據類型的方法的值時,它僅在方法內更改,而在外部保持不變。 我想知道是否有某種方法可以在方法中實際進行更改。 例如:

public class Change {

    void convert(boolean x, boolean y, boolean z) { //i want to set x,y, and z to false in this 
        x = false;
        y = false;
        z = false;
     }

}

//Now in my main class: 
public static void main(String[] args) {
    boolean part1 = true;
    boolean part2 = true;
    boolean part3 = true;
    System.out.println(part1 + " " + part2 + " " + part3);


    Change myChange = new Change();
    myChange.convert(part1,part2,part3);
    System.out.println(part1 + " " + part2 + " " + part3);

}

編輯1:這些答案很好,但不是我想要達到的目標。 我想在調用方法時放入part1,part2和part3,而不是希望在方法中將它們設置為false。 我問這個問題的具體原因是因為我試圖編寫一艘戰艦的代碼,並且我有一個子例程類,該類具有一個方法,當調用它時它會檢查是否沉沒了船只。 如果存在一個接收器,則該方法會將大量布爾變量設置為false。

EDIT2:只是為了澄清,我想要這樣的東西:

void convert(thing1,thing2,thing3,thing4) {

     //some code here that sets thing1,thing2,thing3, and thing4 to false

 }

 // than in main:
 boolean test1 = true;
 boolean test2 = true;
 boolean test3 = true;
 boolean test4 = true;
 convert(test1,test2,test3,test4);
 System.out.println(test1 + " " + test2 + "....");
 //and that should print out false, false, false, false

您可以使用此方法進行操作

// these are called instance variables
private boolean x = false;
private boolean y = false;
private boolean z = false;

// this is a setter
public static void changeBool(boolean x, boolean y, boolean z) {
    this.x = x;
    this.y = y;
    this.z = z;
}

像這樣調用方法

changeBool(true, true, false);

x,y和z的值現在已更改。

這是Java中的常見問題-值傳遞與引用傳遞。 Java始終是按值傳遞,您在這里將其視為按引用傳遞。

就像@Rafael所說的那樣,您需要使用實例變量來執行所需的操作。 我走得更遠,編輯您的源代碼以執行您想要的操作:

public class Change {
boolean part1;
boolean part2;
boolean part3;

Change(boolean x, boolean y, boolean z) {
    part1 = x;
    part2 = y;
    part3 = z;
}

void convert(boolean x, boolean y, boolean z) { //this now sets the class variables to whatever you pass into the method 
    part1 = x;
    part2 = y;
    part3 = z;
}

// Now in my main class:
public static void main(String[] args) {
    Change myChange = new Change(true, true, true);
    System.out.println(myChange.part1 + " " + myChange.part2 + " "
            + myChange.part3);
    myChange.convert(false, false, false);
    System.out.println(myChange.part1 + " " + myChange.part2 + " "
            + myChange.part3);

}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM