有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java“数组索引超出范围异常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

你能帮我解释一下吗


共 (4) 个答案

  1. # 1 楼答案

    for (int x = 0; x < 6; x = x+1)
    
  2. # 2 楼答案

    您的days数组包含6个元素,这意味着它们将从0到5(包括0)进行索引

    您的for循环应该如下所示:

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

    或者更好:

    for (int x = 0; x < day.length; x++)
    
  3. # 3 楼答案

    数组索引总是以0开头,所以如果数组中有7个元素,最后一个元素索引将是7-1 ie 6

    所以改变你的代码:

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

    for (int x = 0; x<day.length; x++)
    
  4. # 4 楼答案

    数组的大小为6,因此索引为0-5

    使用:

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

    对于任何数组长度,或将Friday添加到String [] day