use*_*869 7 java boolean primitive-types
我对Java中的布尔值有疑问.假设我有一个这样的程序:
boolean test = false;
...
foo(test)
foo2(test)
foo(Boolean test){
test = true;
}
foo2(Boolean test){
if(test)
//Doesn't go in here
}
Run Code Online (Sandbox Code Playgroud)
我注意到在foo2中,布尔测试没有改变,因此不会进入if语句.那我怎么去换呢?我查看了布尔值但我找不到一个将测试从"设置"为true的函数.如果有人能帮助我,这将是伟大的.
你将一个原始布尔值传递给你的函数,没有"引用".所以你只是在你的foo方法中隐藏价值.相反,您可能想要使用以下之一 -
持有人
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);
}
Run Code Online (Sandbox Code Playgroud)
哪个输出"在测试中".
或者,通过使用
成员变量
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();
}
Run Code Online (Sandbox Code Playgroud)
其中,也输出"在测试中".
| 归档时间: |
|
| 查看次数: |
13115 次 |
| 最近记录: |