簡體   English   中英

線程“main”中的異常 java.lang.ArrayIndexOutOfBoundsException

[英]Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException

我只是一個java新手,所以請幫助我,我認為問題出在switch stament上

    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());

在這部分 System.out.println(customer[i]+"."); 不管用

    switch(choice){
        case 1:
            System.out.println("This is to display the transaction!");
                            System.out.println(customer[i]+"."); \
                   break;
        case 2:
                 System.out.println("This is to pay the water bill!");
                break;
        default:                                                        System.out.println("Exit`!");
            break;

            }

}

}

問題是當你退出循環時, i的值是 2,而不是 1。

增量表達式在循環的每次迭代后調用。

所以當訪問System.out.println(customer[i]+"."); 由於數組的最后一個元素位於索引 1(數組的基數索引為 0),因此您越界了。

如果你使用這段代碼:

int i;
for(i = 0; i < 2; i++){}
System.out.print(i);

它輸出 2。

那時變量i已經增加到2所以你必須先重置它。 當然,您會遇到 IOOB 異常,因為您正在引用數組中缺少的位置(僅存在01

這是您的代碼的工作方式:

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 語句時,會發生以下情況:

switch(2) { //ALWAYS
..........
..........
}

因此,永遠不會到達switch(1)情況或System.out.println(customer[i]+".") 這是一個很常見的錯誤。

您需要的是菜單的 do while 循環。

所以 :

// 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);

do while確保無論如何,您的命令都將在給出菜單時執行。 因此,例如,在do while ,您的default退出語句將始終打印。

暫無
暫無

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

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