螺纹“中的异常;主&x201D;java.lang.ArrayIndexOutOfBoundsException
我只是一个java新手,所以请帮帮我,我想问题出在开关板上螺纹“中的异常;主&x201D;java.lang.ArrayIndexOutOfBoundsException,java,switch-statement,Java,Switch Statement,我只是一个java新手,所以请帮帮我,我想问题出在开关板上 String customer[]=new String[2]; int old[]=new int[2]; for(i=0; i<customer.length;i++){ System.out.println("\nEnter information of customer#" +(i+1)); System.out.print("Enter customer name
String customer[]=new String[2];
int old[]=new int[2];
for(i=0; i<customer.length;i++){
System.out.println("\nEnter information of customer#" +(i+1));
System.out.print("Enter customer name"+(i+1)+":");
customer[i]=data.readLine();
System.out.print("Enter old reading of costumer#"+(i+1)+":");
old[i]=Integer.parseInt(data.readLine());
}
System.out.println("\n\nSample Menu");
System.out.println("1. Display Transaction\n2.Pay Water Bill");
System.out.print("Enter your choice:");
choice=Integer.parseInt(data.readLine());
}
}问题在于,当退出循环时,
i
的值是2,而不是1
增量表达式在通过
循环
所以当访问System.out.println(客户[i]+”)时代码>由于数组的最后一个元素位于索引1(数组的基索引为0),因此超出了界限
如果您使用这段代码:
int i;
for(i = 0; i < 2; i++){}
System.out.print(i);
inti;
对于(i=0;i<2;i++){}
系统输出打印(一);
它输出2。此时变量i
已增加到2
,因此必须先重置它。当然,您会得到IOOB异常,因为您引用的是数组中缺少的位置(只有位置0
和1
存在)这就是代码的工作方式:
for(i=0; i<customer.length;i++){
............................
............................
}
Hence, i takes values :
i is (i < customer.length)
0 YES
1 YES
2 NO <LOOP BREAKS>
因此,开关(1)
案例或系统.out.println(客户[i]+”)
永远无法到达。这是一个很常见的错误
您需要的是菜单的do while循环
因此:
//初始化值
对于(i=0;i@user3460287通过System.out.println(客户[i]+”)您想做什么;
?我需要打印客户和old@user3460287但是哪个客户?第一个还是第二个?第一个输出必须是此输入信息#1输入客户名称:ME输入旧读数:25输入新读数:59欢迎使用水费计费系统1.显示交易2.支付水费输入您的选择:1客户名称//我需要打印this@user3460287如果要打印第一个客户,请使用System.out.println(客户[0]+”);
。如果要打印第二个客户,请使用System.out.println(客户[1]+”);
。例如,将i==0
放在开关前。虽然此代码对我来说毫无意义。它可以工作,但没有出现一个单词,但我需要打印我输入的客户
for(i=0; i<customer.length;i++){
............................
............................
}
Hence, i takes values :
i is (i < customer.length)
0 YES
1 YES
2 NO <LOOP BREAKS>
switch(2) { //ALWAYS
..........
..........
}
// Initialize Values
for(i=0; i<customer.length;i++){
............................
............................
}
// Loop through the Options
do {
// ASK FOR USER INPUT AS YOU ARE DOING
switch(choice) { //ALWAYS
..........
..........
}
} while(choice != 1 || choice != 2);