改变布尔值? [英] Change boolean Values?

查看:115
本文介绍了改变布尔值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆