【问题标题】:Printing toString information out of List made of different objects从由不同对象组成的 List 中打印 toString 信息
【发布时间】:2018-06-27 14:03:58
【问题描述】:

我在如何解决这个问题上遇到了一些问题。 我有一个 Boat 类,其中包含一个 toString() 和 getter 和 setter。 PowerBoat 类,它扩展了其超类的功能并覆盖了 toString() 方法。 SailBoat 类,它扩展了功能并覆盖了它的超类中的 toString() 方法。 在我的测试类中,我在船类型的 ArrayList 中添加了不同的 PowerBoats、SailBoats。 我需要找到最昂贵的船并打印关于该船的 toString() 信息。

public class Boat {
    String color;
    int length;

    public Boat(){
        color = "white";
        length = 20;
    }

    public Boat(String color, int length){
        setColor(color);
        setLength(length);
    }

    public String getColor() {
        return color;
    }

    public boolean setColor(String color) {
        switch (color){
            case "white" : this.color = color;
            case "red" : this.color = color;
            case "blue" : this.color = color;
            case "yellow" : this.color = color;
            return true;
        }
        return false;
    }

    public int getLength() {
        return length;
    }

    public boolean setLength(int length) {
        if(length >= 20 && length <= 50) {
            this.length = length;
            return true;
        }
        return false;
    }

    @Override
    public String toString() {
        return "Boat{" +
                "color='" + color + '\'' +
                ", length=" + length +
                '}';
    }
}

public class PowerBoat extends Boat {
    int engineSize;

    public PowerBoat(){
        super();
        setEngineSize(5);
    }

    public PowerBoat(String color, int length, int engineSize){
        super(color, length);
        setEngineSize(engineSize);
    }

    public boolean setEngineSize(int engineSize){
        if(engineSize >= 5 && engineSize <= 350){
            this.engineSize = engineSize;
            return true;
        }
        return false;
    }

    public int getEngineSize() {
        return engineSize;
    }

    public int calcPrice(){
        return 5000 + length + 300 + engineSize * 20;
    }

    @Override
    public String toString() {
        return super.toString() +
                "engineSize= " + engineSize +
                '}' + " Price " + calcPrice();
    }
}


    public class SailBoat extends Boat {
        int numSails = 0;

        public SailBoat(){
            numSails = 1;
        }

        public SailBoat(String color, int length, int numSails){
            super(color, length);
            setNumSails(numSails);
        }

        public int getNumSails() {
            return numSails;
        }

        public boolean setNumSails(int numSails) {
            if(numSails >= 1 && numSails <= 4){
                this.numSails = numSails;
                return true;
            }
            return false;
        }

        public int calcPrice(){
            return length * 1000 + numSails * 2000;
        }

        @Override
        public String toString() {
            return super.toString() +
                    "numSails= " + numSails +
                    '}' + " price " + calcPrice();
        }
    }

    public class Inventory {
        public static void main(String[] args){
            ArrayList<Boat> list = new ArrayList();
            Boat powerBoat = new PowerBoat("blue", 46, 60);
            Boat powerBoat1 = new PowerBoat("yellow", 42, 55);
            Boat sailBoat = new SailBoat("white", 32, 1);
            Boat sailBoat1 = new SailBoat("red", 24, 2);
            list.add(powerBoat);
            list.add(powerBoat1);
            list.add(sailBoat);
            list.add(sailBoat1);

            int sumSailBoat = 0;
            int sumPowerBoat = 0;
            int largest = Integer.MIN_VALUE;

            for(Boat b : list){
                if (b instanceof SailBoat){
                    sumSailBoat+= ((SailBoat) b).calcPrice();
                    if (((SailBoat) b).calcPrice() > largest){
                        if(b instanceof SailBoat) {
                            largest = ((SailBoat) b).calcPrice();
                        }
                    }
                }
                if (b instanceof PowerBoat){
                    sumPowerBoat+= ((PowerBoat) b).calcPrice();
                    if(((PowerBoat) b).calcPrice() > largest){
                        if(b instanceof PowerBoat){
                            largest = ((PowerBoat) b).calcPrice();
                        }
                    }
                }
            }

            int totalSum = sumSailBoat + sumPowerBoat;
            System.out.println("Total price of sail boats is " + sumSailBoat);
            System.out.println("Total price of sail boats is " + sumPowerBoat);
            System.out.println("Total price of sail and power boats is " + totalSum);
            System.out.println("Most expensive boat is " + largest);
        }
    }

我设法找到了最高价格,但如何打印关于该船的 toString 信息?

【问题讨论】:

    标签: java oop


    【解决方案1】:

    如果你知道你可以使用的类型:

    System.out.println("My PowerBoat " + ((PowerBoat) b));

    System.out.println("My SailBoat " + ((SailBoat) b));

    【讨论】:

      【解决方案2】:

      如果您已经找到需要打印的对象,请将其存储在一个变量中,然后在其上调用 toString。

      Boat b = //whichever one you found here from the arraylist

      System.out.println(b.toString())

      由于java中的类使用动态绑定,即使你引用的是超类,方法的内容应该还是一样的。

      【讨论】:

      • 我能得到的最好的结果是从 PowerBoats 中获得最大的价格,从 SailBoats 中获得最大的价格。问题是比较最大的 PowerBoat 价格和最大的 SailBoat 价格,请看一下我的 Inventory 类,我想你会明白我的意思
      • 我明白了,您的问题是 Boat 类没有 calcPrice 方法,您可以在其中添加一个并返回任意值,例如 0 或 null。此外,如果您根本不需要在程序中实例化船类,则可以将其设为抽象类。请参阅 Arkadiy 帖子中的第二点
      【解决方案3】:

      [teach-me]你好像对OO设计和java方法调用有一些误解。请与您的老师交谈或阅读一些 OO/Java 书籍。从 Java 中的 abstractfinal 的概念开始 - 这应该让您了解如何调用方法以及如何使用继承。

      话虽如此,你需要做两件事。

      (1)回答你的问题,除了int largest,还保留Boat mostExpensiveBoat,在更新largest的同时更新。然后在最后打印mostExpensiveBoat.toString()

      (2) 需要将 calcPrice() 设为Boat 的抽象方法。那么当你调用b.calcPrice() 时,匹配b 引用的对象类型的方法将“神奇地”被调用。无需检查instanceof 或强制转换。

      【讨论】:

      • 感谢您的反馈,我知道我对 OO 的理解不是最好的。现在从您的建议中,我更好地理解了抽象一词。你有什么好书可以让我更好地理解 OO 吗?
      • 我是通过研究一个优秀的 OO GUI 框架的源代码来学习我的 OO 的,所以我没有书 :) 。从那以后我读过的所有书都只是“如何做好”,而不是“它是什么”。一种可能的建议是学习 Smalltalk - 原始的 OO 语言。无论如何,大约 10 年前,OO 发生了一场革命,当我们终于意识到类的继承是有害的,我们应该使用组合和接口,
      • 好东西,听起来很有希望!
      【解决方案4】:

      最好把 calcPrice() 作为 Boat 接口的一部分:

      abstract class Boat {
          String color;
          int length;
      
          public Boat(){
              color = "white";
              length = 20;
          }
      
          public Boat(String color, int length){
              setColor(color);
              setLength(length);
          }
      
          public String getColor() {
              return color;
          }
      
          public boolean setColor(String color) {
              switch (color){
                  case "white" : this.color = color;
                  case "red" : this.color = color;
                  case "blue" : this.color = color;
                  case "yellow" : this.color = color;
                  return true;
              }
              return false;
          }
      
          public int getLength() {
              return length;
          }
      
          public boolean setLength(int length) {
              if(length >= 20 && length <= 50) {
                  this.length = length;
                  return true;
              }
              return false;
          }
      
          public abstract int calcPrice();
      
          @Override
          public String toString() {
              return "Boat{" +
                      "color='" + color + '\'' +
                      ", length=" + length +
                      '}';
          }
      }
      

      那么就可以这样搜索了:

          int sumSailBoat = 0;
          int sumPowerBoat = 0;
          int largest = Integer.MIN_VALUE;
          Boat boatWithLargestPrice = null;
      
          for (Boat b : list) {
              int boatPrice = b.calcPrice();
              if (boatPrice > largest) {
                  largest = boatPrice;
                  boatWithLargestPrice = b;
              }
      
              if (b instanceof SailBoat) {
                  sumSailBoat += boatPrice;
              } else {
                  sumPowerBoat += boatPrice;
              }       
          }
      
          int totalSum = sumSailBoat + sumPowerBoat;
          System.out.println("Total price of sail boats is " + sumSailBoat);
          System.out.println("Total price of power boats is " + sumPowerBoat);
          System.out.println("Total price of sail and power boats is " + totalSum);
          System.out.println("Most expensive boat is " + boatWithLargestPrice + " with price " + largest);
      

      【讨论】:

      • 谢谢你的回答,我会赞成,但我的声誉
      【解决方案5】:

      通过将Boat 类设为abstract,您可以要求所有Boats 实现calcPrice。然后你就可以对所有Boats 一样对待。

      public abstract class Boat {
          final String color;
          final int length;
      
          public Boat(String color, int length) {
              this.color = color;
              this.length = length;
          }
      
          public abstract int calcPrice();
      
          @Override
          public String toString() {
              return "Boat{" +
                      "color='" + color + '\'' +
                      ", length=" + length +
                      '}';
          }
      }
      
      public class PowerBoat extends Boat {
          final int engineSize;
      
          public PowerBoat(String color, int length, int engineSize) {
              super(color, length);
              this.engineSize = engineSize;
          }
      
          @Override
          public int calcPrice() {
              return 5000 + length + 300 + engineSize * 20;
          }
      
          @Override
          public String toString() {
              return super.toString() +
                      "engineSize= " + engineSize +
                      '}' + " Price " + calcPrice();
          }
      }
      
      public class SailBoat extends Boat {
          final int numSails;
      
          public SailBoat(String color, int length, int numSails) {
              super(color, length);
              this.numSails = numSails;
          }
      
          @Override
          public int calcPrice() {
              return length * 1000 + numSails * 2000;
          }
      
          @Override
          public String toString() {
              return super.toString() +
                      "numSails= " + numSails +
                      '}' + " price " + calcPrice();
          }
      }
      
      public void test() {
          ArrayList<Boat> list = new ArrayList();
          list.add(new PowerBoat("blue", 46, 60));
          list.add(new PowerBoat("yellow", 42, 55));
          list.add(new SailBoat("white", 32, 1));
          list.add(new SailBoat("red", 24, 2));
      
          Boat mostExpensiveBoat = null;
          int totalSum = 0;
      
          for (Boat boat : list) {
              totalSum += boat.calcPrice();
              if(mostExpensiveBoat == null || boat.calcPrice() > mostExpensiveBoat.calcPrice() ) {
                  mostExpensiveBoat = boat;
              }
          }
      
          System.out.println("Total price of sail and power boats is " + totalSum);
          System.out.println("Most expensive boat is " + mostExpensiveBoat);
      }
      

      【讨论】:

      • 通过使您的 Boat 类抽象,您可以要求所有 Boats 实现 calcPrice。那么你就可以对所有的船一视同仁了。 - 非常感谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多