首页 > 解决方案 > 为什么我不能在 toString 方法中返回有价值的字符串类型?

问题描述

我正在尝试为名为 ThreeDVector 的对象编写一个 toString 方法,该方法可以打印出 i、j 和 k 的 3-d 向量,例如“-2i+3.8kj”或“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+")"; 

    }
  }


}

标签: javastringcompiler-errorstostring

解决方案


变量类型没有错,但它们不应该为空。将 s1、s2 和 s3 初始化为方法开头的空字符串toString。另外,不要将它们设置为 null,而是将它们设置为空字符串,在该字符串中您没有获得适当的 x、y 或 z 值。


推荐阅读