有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java创建返回字符串的方法

到目前为止,我的代码如下所示:

public class Tree {
  public static void main (String[] argv) {
    int serial; //create parameters
    double circumference;
    String species;      
  }
  public Tree(int serial, double circumference, String species) {
    String.format("Tree number %d has a circumference of %.2f and is of species %s.", 
        serial, circumference, species);
  }  
}

我不确定如何创建一个describe()方法,该方法返回一个String,其中包含非常特定的格式的树信息


共 (2) 个答案

  1. # 1 楼答案

    方法String.format已经返回了一个String

    public String describe(){
          return String.format("Tree number %d has a circumference of %.2f and is of species %s.", serial, circumference, species);
    }
    

    我建议您重写toString()方法,以提供有关对象的有意义信息

    public String toString(){
        return String.format("Tree number %d has a circumference of %.2f and is of species %s.", serial, circumference, species);
    }
    
  2. # 2 楼答案

    您试图将descripe方法代码放入树构造函数中。不要那样做。使用构造函数初始化字段,然后创建返回格式化字符串的descripe方法

    public class Tree {
      // private Tree fields go here
    
      public Tree(int serial, double circumference, String species) {
        // initialize the Tree fields here
      }
    
      public String describe() {
        // return your formatted String describing the current Tree object here
      }
    }
    

    顺便说一句,您的main方法实际上没有做任何有用的事情,当然也不会创建任何允许您测试descripe方法的树实例