慕桂英4014372
2023-09-27 17:22:14
這應該是一個 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
提交
取消