2017-07-31 79 views
-4

首先,我跳过了员工姓名部分,因此我添加了k.nextLine以消耗\ n之前。 现在我有这样的:为什么在输入最后一个int数组时输入java.lang.ArrayIndexOutOfBoundsExeption?

折扣SUPERMALL

[销售报告]

输入员工数:3

员工姓名:一个

员工销售:1

员工姓名:S

员工销售:2

员工姓名:d

员工销售:3

继承人我所做的:

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]); 
    } 
} 
+2

如果数组大小的'3',您可以使用最后一个可能的索引是'2'('3-1'),因为索引是从0开始 – Shark

+0

应该只使用这个:'系统.out.println(“Name:”+ empName [(numberOfEmp> = 1)? (numberOfEmp-1):0]);' – Shark

回答

1

在最终循环替换:

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

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

为了扩大这个答案,当你创建你的'empName'数组时,你正在创建一个大小为'numberOfEmp'的数组。因为该数组是0索引,所以可以使用数字'0'到'(numberOfEmp - 1)'。如果以6名员工为例,您将'numberOfEmp'设置为6,以便数组具有0-5的有效索引。当你使用'empName [numberOfEmp]'时,你将会执行'empName [6]',它在数组边界之外停止在5,因此java.lang.ArrayIndexOutOfBoundsExeption –

+0

这真的很有帮助谢谢! – det

相关问题