改变布尔值? [英] Change boolean Values?
问题描述
我有一个关于Java中的布尔值的问题。比方说,我有一个程序是这样的:
I have a question about boolean values in Java. Let's say I have a program like this:
boolean test = false;
...
foo(test)
foo2(test)
foo(Boolean test){
test = true;
}
foo2(Boolean test){
if(test)
//Doesn't go in here
}
我注意到,在foo2的,布尔测试并没有改变,因此不进入if语句。我怎么会去改变它呢?我看着布尔值,但我无法找到,将设置测试,从真实的假的功能。如果有人可以帮助我走出这将是巨大的。
I noticed that in foo2, the boolean test does not change and thereby doesn't go into the if statement. How would I go about changing it then? I looked into Boolean values but I couldn't find a function that would "set" test from true to false. If anyone could help me out that would be great.
推荐答案
您是一个原始的布尔值传递给你的函数,没有参考。所以你只有你的阴影富
方法中的价值。相反,你可能需要使用以下步骤之一 -
You're passing the value of a primitive boolean to your function, there is no "reference". So you're only shadowing the value within your foo
method. Instead, you might want to use one of the following -
的的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();
}
其中,还输出测试。
Which, also outputs "In test".
这篇关于改变布尔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!