簡體   English   中英

為什么我的方法多次打印?

[英]Why is my method printing multiple times?

我有三個互不相同的程序。 第一個方法為單個對象創建toString方法,第二個方法讀取包含單個對象列表的文件,第三個方法創建另一個toString方法,該方法調用第一個對象,並創建toString供第二個方法使用。 該信息正在打印多次,我不知道為什么。 iList是一個包含各種對象的數組列表。 我得到的輸出是正確的,但它只打印四次而不是一次。

第一個程序中的toString方法:

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

從第二個程序中的第三個程序調用toString:

Inventory myInventoryList 
     = new Inventory(inventoryName, inventoryList);

  System.out.println(myInventoryList.toString());

您將iList.toString()多次添加到輸出中:

  while (index < iList.size()) {

     output += (iList.toString());  

     index++;
  }

這就是為什么要多次打印的原因。

我不知道iList的類型是iList ,但它看起來像某種列表,因此您可能想在while循環的每次迭代中將列表元素的String表示形式添加到輸出中(而不是每次都有完整列表)。

由於iList是ArrayList,因此您需要將循環更改為:

  int index = 0;
  while (index < iList.size()) {
     output += iList.get(index).toString();   
     index++;
  }

要么 :

  for (int i=0; i<iList.size();i++)
     output += iList.get(i).toString();   

當然,最好將輸出附加到StringBuilder,而不是在每次迭代中創建一個新的String。

這樣做: output += (iList.get(index).toString());

改變這個

while (index < iList.size()) {
  output += (iList.toString());  
  index++;
}

到類似的東西(假設iListList

while (index < iList.size()) {
  output += iList.get(index); // <-- toString() is implicit here  
  index++;
}

這將get(int)要打印的單個項目(而不是每次打印整個List ),並(隱式)調用toString() (您已重寫)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM