繁体   English   中英

arrays 的 toString 方法

[英]toString method for arrays

我正在努力完成一项实际上非常简单的任务,即从项目数组中打印出项目,例如:

arr[3,4,2,5]

0 件 (0 公斤)

0 件 (1 公斤)

0 件 (2 公斤)

等等。 这就是我所做的,但我的程序不会打印任何东西:(请帮帮我。

import java.util.ArrayList;
import java.util.Arrays;

public class Suitcase {
    private ArrayList<Item> items = new ArrayList<>();
    private final int maxWeight;
    private int[] arr = new int[items.size()];

    public Suitcase(int maxWeight) {
        this.maxWeight = maxWeight;
    }

    public void addItem(Item item) {
       int itemsWeight = 0;
       for(Item i: items){
           itemsWeight += i.getWeight();
       }
       if(itemsWeight + item.getWeight() <= this.maxWeight){
            items.add(item);
       }
   }

    public void array() {
        for(Item item: items){
            int index = item.getWeight();
            this.arr[index] += 1;
        }
    }

    public String toString() {
        String returnValue = "";
        for(int i = 0; i < arr.length; i++){
            returnValue = arr[i] + " items " + i + " kg";
        }
        return returnValue;
    }
}

public class Item {
    private int weight;
    private String name;

    public Item(String name, int weight) {
        this.name = name;
        this.weight = weight;
    }
    public String getName() {
        return this.name;
    }
    public int getWeight() {
        return this.weight;
    }
    public String toString() {
        return this.name + "(" + String.valueOf(this.weight) + ")";
    }
}

这是我的主要 class,但它不会打印任何内容:

public class Main {
    public static void main(String[] args) {
        Item book = new Item("Lord of the rings", 2);
        Item phone = new Item("Nokia 3210", 1);
        Item brick = new Item("brick", 4);

        Suitcase suitcase = new Suitcase(5);
        System.out.println(suitcase.toString());

        suitcase.addItem(book);
        System.out.println(suitcase);

        suitcase.addItem(phone);
        System.out.println(suitcase);

        suitcase.addItem(brick);
        System.out.println(suitcase);
    }
}

确保更改您的“toString()”function,目前它只打印最后一个值,将其更改为:

public String toString(){
             String returnValue ="";
            for(int i = 0; i<arr.length;i++ ){
                       returnValue += arr[i] + " items " +i+" kg"; //notice its '+='
            }
                   return returnValue;
}

笔记:

  1. 打印suitcase object 时不需要调用suitcase.toString() System.out.println(suitcase); is 隐式转换为System.out.println(suitcase.toString()); .
  2. 您可以通过一个变量来跟踪手提箱中的总重量,从而使您的设计更简单。 此外,在Item中创建一个变量来跟踪手提箱中的项目计数。
  3. 您不需要int[] arr 它只是增加了不必要的复杂性。 去掉它。
  4. 如果可以的话,最好使用增强的 for 循环

下面给出的是包含上述几点的代码:

import java.util.ArrayList;

class Suitcase {

    private ArrayList<Item> items = new ArrayList<>();
    private final int maxWeight;
    private int totalWeight;

    public Suitcase(int maxWeight) {
        this.maxWeight = maxWeight;
    }

    public void addItem(Item item) {
        if (totalWeight + item.getWeight() <= maxWeight) {
            int index = items.indexOf(item);
            if (index == -1) {// It means the item does not exist in the suitcase
                items.add(item);
            }
            // If the item already exists, do not add it's entry again; just update its
            // count and the totalWeight of the suitcase
            totalWeight += item.getWeight();
            item.setCount(item.getCount() + 1);
            System.out.println(item.getName() + " was added in the suitcase");
        } else {
            System.out.println(item.getName() + " can not be accommodated in the suitcase.");
        }
    }

    public String toString() {
        String returnValue = "";
        for (Item item : items) {
            returnValue += "No. of " + item.getName() + " in the suitcase = " + item.getCount()
                    + ", its total weight = " + item.getCount() * item.getWeight() + "kg\n";
        }
        if (returnValue.isEmpty()) {
            returnValue = "The suitcase is empty.";
        } else {
            returnValue += "Total weight of the suitcase = " + totalWeight + "kg";
        }
        return returnValue;
    }
}

class Item {
    private int weight;
    private String name;
    private int count;

    public Item(String name, int weight) {
        this.name = name;
        this.weight = weight;
    }

    public String getName() {
        return this.name;
    }

    public int getWeight() {
        return this.weight;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    @Override
    public String toString() {
        return "Item [weight=" + weight + ", name=" + name + ", count=" + count + "]";
    }
}

public class Main {
    public static void main(String[] args) {
        Item book = new Item("Lord of the rings", 2);
        Item phone = new Item("Nokia 3210", 1);
        Item brick = new Item("brick", 4);

        Suitcase suitcase = new Suitcase(5);
        System.out.println(suitcase);

        suitcase.addItem(book);
        suitcase.addItem(phone);
        suitcase.addItem(brick);
        suitcase.addItem(phone);
        suitcase.addItem(book);
        System.out.println(suitcase);
    }
}

Output:

The suitcase is empty.
Lord of the rings was added in the suitcase
Nokia 3210 was added in the suitcase
brick can not be accommodated in the suitcase.
Nokia 3210 was added in the suitcase
Lord of the rings can not be accommodated in the suitcase.
No. of Lord of the rings in the suitcase = 1, its total weight = 2kg
No. of Nokia 3210 in the suitcase = 2, its total weight = 2kg
Total weight of the suitcase = 4kg

如有任何疑问/问题,请随时发表评论。

你用值0初始化你的arr 请注意, new ArrayList()的初始大小为0 看看这个例子:

import java.util.ArrayList;

class Main {
  private static ArrayList<Object> items = new ArrayList();
  private static int[] arr = new int[items.size()];
  public static void main(String[] args) {
    System.out.println(items.size()); # => 0
    System.out.println(arr.length); # => 0
  }
}

因此,当您调用System.out.println(suitcase)时, SuitcasetoString()方法中的for循环恰好迭代 0 个元素 - 因此不输出任何内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM