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.
推荐答案
您将原始布尔值传递给您的函数,没有引用".因此,您只是在 foo
方法中隐藏值.相反,您可能想要使用以下之一 -
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 -
持有人
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();
}
其中,也输出In test".
Which, also outputs "In test".
这篇关于更改布尔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:更改布尔值?
基础教程推荐
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 降序排序:Java Map 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01