为什么我不能 return 一个在 toString 方法中有价值的字符串类型?

Why I can not return a string type valuable in a toString Method?

我正在尝试为一个名为 ThreeDVector 的对象编写一个 toString 方法,它可以根据 i、j 和 k 打印出一个 3 维向量,例如“-2i+3.8k-j”或“7i-5j” ”。然而,在第 96 行,总是有一个错误说 s1、s2 和 s3 可能没有被初始化。由于我已经初始化了它,我猜想这些变量的变量类型有问题,但我不明白如何修复它。

class ThreeDVector
{
  double x;    // x-component of vector
  double y;    // y-component of vector
  private double z;  // z-component of vector
// For the purposes of this lab the z component must be between -1000 
// and 1000 (non-inclusive). 

  public ThreeDVector(){
    x=0; 
    y=0;
    z=0;
  }
  public ThreeDVector(double x, double y, double z)
  {
    this.x = x;
    this.y = y;
    if (z>(-1000)&&z<(1000))
      this.z = z;
    else{
      throw new RuntimeException(); 
    }
  }

  public void setZvalue(double z) throws Exception
  {
    if( z>(-1000)&&z<1000 )
      this.z= z;
    else{
      throw new Exception("z value has to be in the range of -1000 to 1000, non-inclusve");
    }
  }


  public boolean isWholenum (double n){
    if(Math.round(n) == n)
      return true;
    else 
      return false;
  }

  public String toString(){

    String s1, s2, s3;

    if(this.z>=1000||z<=(-1000)){
      return "undefied";
    }else{
      if (x!=0){
        if(isWholenum(x)==true){
          s1=String.valueOf(Math.round(x))+"i";
        }else{
          s1=String.valueOf(String.format("%.3f", x))+"i";
        }
      }else if (x==0)
        s1=null;//if the coefficient is 0, do not print out that term 

      if (y>0){
        if(isWholenum(y)==true){
          s2="+"+String.valueOf(Math.round(y))+"j";
        }else{
          s2="+"+String.valueOf(String.format("%.3f", y))+"j";
        }
      }
      else if (y==0)
        s2=null; 
      else if (y<0){
        if(isWholenum(y)==true){
          s2="-"+String.valueOf(Math.round(y))+"j";
        }else{
          s2="-"+String.valueOf(String.format("%.3f", y))+"j";
        }
      } 
      if (z>0){
        if(isWholenum(z)==true){
          s3="+"+String.valueOf(Math.round(z))+"k";
        }else{
          s3="+"+String.valueOf(String.format("%.3f", y))+"k";
        }
      }
      else if (z==0)
        s3=null; 
      else if (z<0){
        if(isWholenum(z)==true){
          s3="-"+String.valueOf(Math.round(z))+"k";
        }else{
          s3="-"+String.valueOf(String.format("%.3f", z))+"k";
        }
      } 


      return "("+ s1+s2+ s3+")"; 

    }
  }


}

变量类型没有问题,但不能为null。在 toString 方法的开头将 s1、s2 和 s3 初始化为空字符串。此外,不要将它们设置为 null,而是将它们设置为空字符串,在这种情况下您无法获得合适的 x、y 或 z 值。

而不是:

String s1, s2, s3;

使用:

String s1 = "", s2 = "", s3 = "";

此外,我不会使用您将其中一个字符串设置为 null 的条件块,因为将它们初始化为空字符串会使此操作变得多余。在它们的每个条件前放置一个 !,并将它们添加到将字符串设置为不同值的块中。