2017-02-04 2 views
2

내 모듈에 입력 된 모듈 수에 대한 사용자 입력에 따라 배열의 크기가 고정되어 있지 않으므로이 코드를 실행하고이 오류가 발생했을 때 수행 할 작업을 실제로 알지 못합니다. ArrayIndexOutOfBoundsException : 0ArrayIndexOutOfBoundsException : 0 오류

Module[] array = new Module[moduleno]; 
    String[] a = new String[moduleno]; 
    String[] b = new String[moduleno]; 
    int[] c = new int[moduleno]; 
    String[] Output = new String[moduleno]; 
    String endoutput=""; 

    //Method for input of number of modules 
    moduleno = Student.modno(); 

    for (int i = 0; i < moduleno; i++) { 

      modulename = Student.MakingModName(i); 
      grade = Student.readGrade(i); 
      cu = Student.readCredits(i); 
      value = Student.GradeValue(grade); 
      score = Student.calculateScore(value, cu); 
      totalScore += score; 
      totalCu += cu; 
      GPA = Student.calculateGPA(totalCu, totalScore); 

      //Error occurs here. 
      **array[i] = new Module(modulename,grade,cu);** 
      a[i] = array[i].getModulename(); 

      b[i] = array[i].getGrade(); 
      c[i] = array[i].getCu(); 


      Output[i] = a[i] + "    " +b[i]+"    " +c[i]+"    "; 
      endoutput = endoutput + Output[i] + "\n"; 
     } 
+1

어떤 줄에서 오류가 발생합니까 –

+0

배열이 초기화되고 어느 것이 오류의 원인입니까? –

+0

"고정되지 않은 배열 크기"란 무엇입니까? 길이가 0 인 배열을 만든 것 같습니다. – Henry

답변

4

문이 순서 :

Module[] array = new Module[moduleno]; 
moduleno = Student.modno(); 

마술 이전에 할당 된 배열의 크기를 조정하지 않습니다. 당신은 라운드 그것을 다른 방법을 수행해야 당신이 당신의 배열을 초기화하기 전에

moduleno = Student.modno(); 
Module[] array = new Module[moduleno]; 
1
가 문을

moduleno = Student.modno(); // this should be the value while you initialize the array 

이동

.

0
//Add This line before initialize your array 
**moduleno = Student.modno();** 

Module[] array = new Module[moduleno]; 
String[] a = new String[moduleno]; 
String[] b = new String[moduleno]; 
int[] c = new int[moduleno]; 
String[] Output = new String[moduleno]; 
String endoutput=""; 

이유 : 당신의 모든 배열의 크기는 0 (제로) 그래서 기본적으로moduleno 변수는 0 (제로)의 크기가 포함되어 있습니다.

배열에 1 요소를 추가하려고하지만 배열의 크기가 0이므로 ArrayIndexOutBoundsException을 제공합니다.

관련 문제