我的目标是建立一个程序,要求所有相关信息来创建发票。如果用户希望添加另一个产品/服务,程序将循环并且阵列将递增,以便输出将提供所有产品的描述和价格。运行此代码时,当我尝试添加产品说明时出现此错误:
线程中的异常" 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 :(得分:0)
您正在初始化String[] description = new String[descnum];
根据您的代码,您已初始化descnum = 1
,因此它将创建一个大小为1的数组,并且您尝试访问description[descnum++] = Keyboard.readString();
,即超出初始化数组的范围
尝试将description[descnum++] = Keyboard.readString();
更改为description[0] = Keyboard.readString();
或增加数组的大小