为什么在输入最后一个int数组时会说java.lang.ArrayIndexOutOfBoundsExeption?

时间:2017-07-31 16:19:51

标签: java arrays

首先,我跳过了Employee的Name部分,所以我添加了k.nextLine以消耗之前的\ n。 现在我有了这个:

折扣优惠

[销售报告]

输入员工人数:3

员工姓名:A

员工销售:1

员工姓名:S

员工销售:2

员工姓名:D

员工销售额:3

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at Case_Study.main(Case_Study.java:22)

继承人的所作所为:

public static void main(String[] args)
    {   Scanner k = new Scanner(System.in);
    System.out.println("DISCOUNT SUPERMALL");
    System.out.println(" [Sales Report]");
    System.out.print("Enter number of Employee: ");
    int numberOfEmp = k.nextInt();
    String[] empName = new String [numberOfEmp];
    double[] empSale = new double [numberOfEmp];

    for(int a=0; a<numberOfEmp; a++)
    {   System.out.print("Employee Name:    ");
        k.nextLine();
        empName[a] = k.nextLine();
        System.out.print("Employee's Sales: ");
        empSale[a] = k.nextDouble();
    }   System.out.println();


    for (int c=0; c<numberOfEmp; c++)
    {   System.out.println("Name:  "+empName[numberOfEmp]);
        System.out.println("Sales: "+empSale[numberOfEmp]);
    }
}

1 个答案:

答案 0 :(得分:1)

在你的最后一个循环中替换:

System.out.println("Name:  "+empName[numberOfEmp]);

System.out.println("Name:  "+empName[c]);