2013-05-21 35 views
-3

此代碼有效,但有一件事。它編譯沒有錯誤,但之後我試圖運行它,它給我一個例外:「數組索引超出界限例外6」

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6 at JavaJoe.main(JavaJoe.java:3) 

這是代碼:

import java.text.DecimalFormat; 
import java.text.NumberFormat; 

public class JavaJoe 
{ 

public static void main(String[] args)  { 

double money = 200; 
double area = 0; 
double money1 = 0; 
double money2 = 0; 
double money3 = 0; 

String [] day = {"Monday", "Tuesday", "Wednesday", "Thursday", 
"Saturday", "Sunday"}; 

NumberFormat decimal = new DecimalFormat("$###.00"); 
NumberFormat decimal1 = new DecimalFormat("###.0"); 

for (int x = 0; x <= 6; x = x+1) 
{ 
    if(day[x].equals("Monday")) 
    { 
     double totalCost = 30 * 1.15; //cost including tax 
     money = money - totalCost; 
     System.out.println("It is " + day[x] + " and Joe has to spend " +  decimal.format(totalCost) + " on a new pair of shoes. He has " + decimal.format(money) + " left."); 

    } else if(day[x].equals("Tuesday")) 
    { 
     area = 12 * 7; 
     System.out.println("It is " + day[x] + ". The ceiling Joe wants to paint is " + area + " metres squared."); 

    } else if(day[x].equals("Wednesday")) 
    { 
     double price = 1.13 * area; //how much money he spent on paint per square litre 
     money1 = money - price; 
     System.out.println("It is " + day[x] + ". Joe spends " + decimal.format(price) + " on paint. He has " + decimal.format(money1) + " left."); 

    } else if(day[x].equals("Thursday")) 
    { 
     double gasPrice = 36.40; 
     double litresGas = gasPrice/0.45; //calculation to find how many litres he bought 
     money2 = money1 - gasPrice; 
     System.out.println("It is " + day[x] + ". Joe spends " +decimal.format(gasPrice) + " on gas and buys " + decimal1.format(litresGas) + " litres. He has " + decimal.format(money2) + " left."); 

    } else if(day[x].equals("Saturday")) 
    { 
     double charity = 23; //money he spent on charity 
     money3 = money2 - charity; 
     System.out.println("It is " + day[x] + ". Joe donates " + decimal.format(charity) + " to charity. He has " + decimal.format(money3) + " left."); 

    }else if(day[x].equals("Sunday")) 
    { 
     System.out.println("Today is " + day[x] + "."); 
    } //if 

} //for 

} //main 

} //class 

你能幫助我,並解釋一下嗎?

+0

http://stackoverflow.com/editing-help#code – SLaks

+2

'的String [] day'缺少週五 – Zutty

回答

1

您陣列的大小爲,因此索引爲0-5

使用:

for (int x = 0; x < day.length; x++) 

任何陣列的長度,或添加FridayString [] day

+1

謝謝!這很有道理。 – Salma

-2
for (int x = 0; x < 6; x = x+1) 
3

days陣列包含6個元素,這意味着它們會從0索引到5(含)。

您的循環應該是這樣的:

for (int x = 0; x < 6; x = x+1) 

甚至更​​好:

for (int x = 0; x < day.length; x++) 
3

數組的索引總是從0開始,所以如果有一個7元的數組中,最後一個元素的索引將7-1即6

所以更改代碼:

for (int x = 0; x <= 6; x = x+1) 

for (int x = 0; x<day.length; x++)