【问题标题】:toString and booleans [duplicate]toString 和布尔值 [重复]
【发布时间】:2016-05-18 08:07:20
【问题描述】:

我正在为灯泡做一个课程,我必须让它处于开/关状态,无论它是否烧坏,以及它的颜色。无论出于何种原因,我得到了正确的切换,但是我的 toString 打印了错误的答案,我不知道为什么。我不习惯使用布尔值,所以我的代码可能不支持我的逻辑。有人可以帮忙吗?

代码如下:

public class Light
{
 // Variables that will be initialized in the Light constructors.

 private boolean on;
 private boolean burntOut;
 private String color = "";

 // Default constructor that sets the bulb to on, not burnt out, and "white".

 public Light()
 {
  on= true;
  burntOut = false;
  color = "white";
 }

 // This constructor sets the variable "on" to the parameter o. The burntOut
 // variable is set to the parameter b. If burntOut
 // is true, on is set to false, no matter what value is stored in o.
 // The color variable is set to the parameter c only if c is "red", "green"
 // or "blue". The constructor ignores the case of the value in c. If c holds
 // any value other than "red", "green" or "blue", the constructor sets
 // color to "white".

 public Light(boolean o, boolean b, String c)
 {
on = o;
burntOut=b;
  if(burntOut=true){
    on = false;
  }
  else{
    on= o;
  }
  if(c.equalsIgnoreCase("red")){
    color = "red"; 
  }
  if(c.equalsIgnoreCase("blue")){
    color = "blue";
  }
  if (c.equalsIgnoreCase("green")){
    color="green";
  }
  else {
    color = "white";
  }

 }

 // The toString method returns a String with the Light in the format:
 // off red    burnt out
 // on green    not burnt out
 //
 // Notice there is one space between "off"/"on" and the value for color,
 // and a tab before the "burnt out" or "not burnt out".

 public String toString()
 {
  String x ="";
       if(on = true){
         x+="on" + " ";
       }
       if(on = false){
         x+= "off" + " ";
       }

       x+= color;

       if (burntOut = false){
         x+="\t" + "not burnt out";
       }
       if(burntOut = true){
         x+= "\t" + "burnt out";
       }


  return x;
 }

这是项目允许我运行以显示我的结果的测试:

> run Light

1。测试灯() * PASS: on 设置正确 (true) PASS:burntOut 设置正确(假) PASS:颜色设置正确(白色) * FAIL: toString 不能按预期工作(白色烧坏)

  1. 测试灯(布尔 b,布尔 o,字符串 c) * PASS: on 设置正确 (false) PASS:burntOut 设置正确(true) PASS:颜色设置正确(绿色) * FAIL: toString 不能按预期工作(绿色烧坏)

【问题讨论】:

  • = 用于赋值。
  • ==,而不是=。或者,更好的是if (on) { ... } else { ... }
  • 这很有意义
  • 这是你犯错的地方,if(burntOut=true){ on = false; } 应该是 if(burntOut == true){ on = false; } 检查每一步是否正确。

标签: java string boolean tostring


【解决方案1】:

这个:

if(on = true){

您不是在比较,而是在分配价值。要进行比较,请使用==

if(on == true){

或者,更简单:

if(on){

(注意:您的代码中有几个地方存在此错误。这仅说明了其中一个。相应地修复其他地方。)

【讨论】:

  • 没错。为此 +1。
  • 这很有道理,谢谢你提醒这么简单的规则!
  • @BobD:在您前进时可能会有所帮助的一件事是考虑变量的语义名称。例如,如果变量on 被称为isOn 之类的代码,那么代码可能类似于:if (this.isOn),它在语义上非常清楚地读作“如果它开启”。
猜你喜欢
  • 1970-01-01
  • 2016-01-30
  • 1970-01-01
  • 2016-07-06
  • 2015-11-01
  • 2013-11-04
  • 2019-02-23
  • 2020-08-14
  • 2013-07-02
相关资源
最近更新 更多