java - 为什么我不能在toString方法中返回有值(value)的字符串类型?

标签 java string compiler-errors tostring

我正在尝试为名为ThreeDVector的对象编写toString方法,该对象可以根据i,j和k打印出3-d vector ,例如“-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初始化为空字符串。另外,不要将它们设置为空字符串,而应将其设置为空字符串,在该字符串中您不会获得x,y或z的适当值。

关于java - 为什么我不能在toString方法中返回有值(value)的字符串类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55887120/

相关文章:

java - 使用 WSDL 从 url 和身份验证实例化 JAX-WS 服务

java - 在 Java 中,这种类型的方法覆盖是什么?

java - 重新分配字符串变量

c++ - 重载输出运算符和后增量运算符时出现不匹配 ‘operator<<’ 错误

java - Java 的 CSS 类

java - java是否也在用户定义的泛型类中实现类型删除?

java:字节码中的字符串concat转换为StringBuilder

java - 在 java 中,多个线程处理相同的字符串列表?

import - 包括一个内部模块产生 "maybe a missing crate ` 模块 2`"

haskell - 为什么会收到类型错误?