如何更改方法中的布尔值 - Java?

时间:2014-12-01 01:41:39

标签: java methods parameters converter return-value

我在一本书中读到,当您更改方法参数的值时,该方法参数在方法中是布尔值或其他基本数据类型,它只在方法中更改并在外部保持不变。我想知道我是否有办法在方法中实际更改它。例如:

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);

}

EDIT1:这些答案很好,但并不是我想要实现的目标。我想在调用方法时放入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

2 个答案:

答案 0 :(得分:0)

您可以使用此方法

// 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的值。

答案 1 :(得分:0)

这是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);

}
}
相关问题