2016-09-22 45 views
-1

我的目標是要一個程序,要求所有相關信息來創建發票。如果用戶希望添加其他產品/服務,程序將循環並且數組將增加,以便輸出將爲所有產品提供描述和價格。如何在一個循環中使用數組,並有多個輸出

異常線程「main」 java.lang.ArrayIndexOutOfBoundsException:1

我希望我解釋清楚我的問題,當運行此代碼時,我嘗試添加產品說明我得到這個錯誤。

import cs1.Keyboard; 

public class Invoice_Obj{ 

    // This object creates an invoice 

    public void invoice(){ 

     char answer; 
     int descnum = 1; 
     int pricenum = 1; 

     System.out.print("Enter invoice #\t\t: "); 
     String invoicenum = Keyboard.readString(); //user inputs the invoice number 

     System.out.print("Enter Date\t\t: "); 
     String date = Keyboard.readString(); //user inputs the date of the invoice 

     System.out.print("Who is this invoice to? : "); 
     String recipient = Keyboard.readString(); //user inputs the recipient of the invoice 

     do{ 

     System.out.print("\nDescription of service or product : "); 
     String[] description = new String[descnum]; 
     description[descnum++] = Keyboard.readString(); 

     System.out.print("\nTotal price of service or product : "); 
     String[] price = new String[pricenum]; 
     price[pricenum++] = Keyboard.readString(); 

     System.out.print("Add another service/product? (Y/N) : "); 
     answer = Keyboard.readChar(); 


     }while(answer=='Y' || answer=='y'); 

    } 

} 
+0

提供堆棧跟蹤以幫助調試問題通常很有幫助。在這種情況下的例外確實有助於我們理解,但堆棧跟蹤可以幫助更多。 – Dale

+0

除了索引錯誤('description [descnum ++]'和'price [pricenum ++]'),您每次都創建一個新數組。可能不是你想要的。考慮使用[ArrayList](https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html)。 –

+0

你定義一個只有一個元素的數組,然後你試圖放置多個不存在的索引的元素。 – PEF

回答

0

要初始化String[] description = new String[descnum];

按你的代碼已經初始化descnum = 1所以它會創建一個大小爲一個數組,你試圖訪問description[descnum++] = Keyboard.readString();即出界初始化數組

嘗試更改description[descnum++] = Keyboard.readString();description[0] = Keyboard.readString();

或增加陣列的大小

相關問題