亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

帶 for 循環的 toString 方法不起作用,不知道為什么

帶 for 循環的 toString 方法不起作用,不知道為什么

慕桂英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 也應該像標準輸出一樣打印它


查看完整回答
反對 回復 2023-09-27
?
MM們

TA貢獻1886條經驗 獲得超2個贊

可能 this.items.size() 即將為零并且返回一個空字符串!



查看完整回答
反對 回復 2023-09-27
  • 2 回答
  • 0 關注
  • 94 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號