这应该是一个 to string 方法,它是其中所有项目的串联,ArrayList但当我调用它时,它根本不执行任何操作。我没有收到任何错误;只是代码根本不做任何事情。我以前有过这个工作,它不是一个 for 循环,它只是toString多次调用该方法,但现在我试图连接所有方法,但toString由于某种原因它不起作用。 import java.util.ArrayList; /*this class creates an object of type catalog used to put items into and defines methods used to manipulate this catalog object*/ public class Catalog { // instance variables - replace the example below with your own private ArrayList<Item> items; private final int MAX = 20; private int size; private int itemNum; /** * Constructor for objects of class Catalog */ public Catalog() { //makes empty arraylist // initialise instance variables items = new ArrayList<>(MAX); size = 0; } /** * An example of a method - replace this comment with your own * * @param y a sample parameter for a method * @return the sum of x and y */ public void addItem(Item theItem) { // put your code here items.add(theItem); size = items.size(); } public Item remItem(int theItem) { Item temp = this.find(theItem); items.remove(temp); size = items.size(); return temp; } public Item find(int itemNum){ for (Item item : this.items){ if (item.getItemNumber() == (itemNum)) { return item; } } return null; } public String toString() { String itemlist = ""; for (int i = 0; i < this.items.size(); i++){ itemlist += items.get(i).toString(); } return itemlist; } public boolean isEmpty(){ return items.isEmpty(); } }
2 回答
慕哥6287543
TA贡献1831条经验 获得超10个赞
使用您的 Item 类更改了测试代码。仍然没有问题
Catalog c = new Catalog();
System.out.println("Empty : " + c.toString());
c.addItem(new Item(1, "abc", 2d));
c.addItem(new Item(2, "def", 3d));
c.addItem(new Item(3, "ghi", 4d));
System.out.println("Not empty : " + c.toString());
使用您提供的 Item 类,现在的输出是
输出 :
Empty :
Not empty : Item number: 1
Item type: Item
Item title: abc
Item price: 2.00
Item number: 2
Item type: Item
Item title: def
Item price: 3.00
Item number: 3
Item type: Item
Item title: ghi
Item price: 4.00
Process finished with exit code 0
尝试编译代码并使用命令行 ( java -jar YourApp.jar ) 运行它,但 IDE 也应该像标准输出一样打印它
添加回答
举报
0/150
提交
取消