java - 数组的 toString 方法

标签 java

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

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) + ")";
    }
}

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

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);
    }
}

最佳答案

注释:

  1. 在打印 suitcase 对象时,您不需要调用 suitcase.toString()。当 System.out.println(suitcase); 隐式转换为 System.out.println(suitcase.toString()); 时。
  2. 您可以通过使用变量来跟踪手提箱中的总重量,从而简化您的设计。另外,在 Item 中创建一个变量来跟踪手提箱中的项目数量。
  3. 您不需要int[] arr。它只是增加了不必要的复杂性。将其删除。
  4. 最好使用 enhanced for loop如果你能做到的话。

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

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);
    }
}

输出:

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

关于java - 数组的 toString 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61084157/

相关文章:

java - 为什么 TwitterLoginButton 在 Android 上不会膨胀?

java - 蓝牙扫描仪在屏幕关闭时停止扫描或减少扫描频率

java - Spring Boot 缓存 SpEL (#result) 返回 Null

java - “找不到符号”错误

java - 在 Maven 构建期间将 Swagger 规范保存到文件

java - 旋转 BufferedImage 时如何产生清晰的绘制结果?

java - 上传到imgur,已经一周失败了

java - 服务和服务提供者接口(interface)有什么区别?

java - Selenium 并不总是能够识别元素何时从 DOM 中删除

跨多个包含 block 的 Java 变量 - 无法解析变量