java数组越界错误
package home_work_4_17; abstract class Employee{ abstract double earnings(); } class YearWorker extends Employee{ double earnings(){ System.out.println("按年领取1000"); return 1000; } } class MonthWorker extends Employee{ double earnings(){ System.out.println("按月领取100"); return 100; } } class WeekWorker extends Employee{ double earnings(){ System.out.println("按星期领取10"); return 10; } } class Company{ int n; //该公司的人数 public Company(int n) { this.n=n;// TODO Auto-generated constructor stub } Employee E[]=new Employee[n]; double cal(){ //返回薪水综合 double sum=0; for(int j=0;j<n;j++){ sum+=E[j].earnings(); } return sum; } } public class work_2 { public static void main(String args[]) { Company c=new Company(3); c.E[0]=new WeekWorker(); c.E[1]=new MonthWorker(); c.E[2]=new YearWorker(); System.out.println("总支出:"+c.cal()); } }
编译器显示数组越界错误。
经检查发现划线部分语句出错
应当做如下修改:
1 class Company{ 2 int n; //该公司的人数 3 Employee E[]; 4 public Company(int n) { 5 this.n=n;// TODO Auto-generated constructor stub 6 E=new Employee[n]; 7 } 8 9 double cal(){ //返回薪水综合 10 double sum=0; 11 for(int j=0;j<n;j++){ 12 sum+=E[j].earnings(); 13 } 14 return sum; 15 } 16 }
出错原因是:当Company构造方法中并未对数组E进行初始化操作,故而E数组大小仍然为0,发生数组越界错误。
利用上述错误方式编写的测试程序如下:
1 package test_a; 2 class people{ 3 int n; 4 Student s[]=new Student[n]; 5 public people(int n) { 6 this.n=n;// TODO Auto-generated constructor stub 7 } 8 9 } 10 11 class Student{ 12 int number; 13 } 14 15 public class Cdcs { 16 public static void main(String args[]) { 17 people p=new people(3); 18 19 System.out.println(p.s.length); 20 } 21 }
输出结果为0。即数组大小为零。
优质内容筛选与推荐>>