Java 为什么我的方法要打印多次?
我有三个不同的程序,它们都是相互读入的。一个方法为单个对象创建一个toString方法,第二个方法读取一个包含单个对象列表的文件,第三个方法创建一个额外的toString方法,该方法调用第一个方法并创建一个toString供第二个方法使用。信息被打印了很多次,我不知道为什么。iList是包含各种对象的数组列表。我得到的输出是正确的,但它只是打印了四次而不是一次 第一个程序中的toString方法:Java 为什么我的方法要打印多次?,java,arraylist,Java,Arraylist,我有三个不同的程序,它们都是相互读入的。一个方法为单个对象创建一个toString方法,第二个方法读取一个包含单个对象列表的文件,第三个方法创建一个额外的toString方法,该方法调用第一个方法并创建一个toString供第二个方法使用。信息被打印了很多次,我不知道为什么。iList是包含各种对象的数组列表。我得到的输出是正确的,但它只是打印了四次而不是一次 第一个程序中的toString方法: public String toString() { NumberFormat dollar
public String toString() {
NumberFormat dollarFmt = NumberFormat.getCurrencyInstance();
DecimalFormat percentFmt = new DecimalFormat("#.0%");
String output = "\nDescription: " + description.trim();
output += "\nCost: " + dollarFmt.format(cost);
output += " Percent Depreciation: "
+ percentFmt.format(percentDepreciated);
output += "\nCurrent Value: "
+ dollarFmt.format(cost - (cost * percentDepreciated));
if (isEligibleToScrape()) {
output += "\n*** Eligible to scrape ***";
}
if (percentDepreciatedOutOfRange()) {
output += "\n*** Percent Depreciated appears to be out of range ***";
}
}
第三个程序中的toString方法:
public String toString() {
String output = ("\n" + inventoryName + "\n");
int index = 1;
while (index < iList.size()) {
output += (iList.toString());
index++;
}
return output;
}
Inventory myInventoryList
= new Inventory(inventoryName, inventoryList);
System.out.println(myInventoryList.toString());
您多次将iList.toString()添加到输出中:
while (index < iList.size()) {
output += (iList.toString());
index++;
}
或:
for(inti=0;i执行以下操作:output+=(iList.get(index.toString());
更改此选项
while (index < iList.size()) {
output += (iList.toString());
index++;
}
要打印的单个项目(而不是每次打印整个列表)和(隐式地)调用toString()
(您已经覆盖了它)。第二个程序在哪里?因为您正在调用toString()
递归地在第二个程序中哦,好的,我明白了。我使用while循环是因为我需要打印iList(InventoryItems)中包含的每个对象。我该怎么做?@kb94 iList的类型是什么?您需要调用一个返回该列表第I项的方法,并在该项上运行toString。iList是一个arraylist。您缺少iList.get(index.toString())
@Rustam不,我没有,它仍然隐式存在,因为输出
是一个字符串
。我认为它没有被重写
,所以它将是一个正常的方法。m I ryt?@Rustam没有被重写
?它仍然隐式调用列表返回的对象上的toString()
谢谢!这就解决了问题。
for (int i=0; i<iList.size();i++)
output += iList.get(i).toString();
while (index < iList.size()) {
output += (iList.toString());
index++;
}
while (index < iList.size()) {
output += iList.get(index); // <-- toString() is implicit here
index++;
}