-2

In the code below I try to get the grade of all my subjects. I get the input via a for loop. But I'm supposed to store the grade ("C" for example) in the grade array but I get a NullPointerException. I don't understand what's wrong with my code since I thought it was good to go. Also, ignore the names of the subjects since they are in Swedish.

public class Defan{

Scanner sc = new Scanner(System.in);
String grade[];
String gradeName[] = {"Svenska1", "Svenska2", "Svenska3", "Engelska5", "Engelska 6",
        "Mattematik 1c", "Mattematik 2c", "Mattematik 3c", "Mattematik 4", "Idrott", "Samhälle", "Religion",
        "Historia", "Biologi1", "Biologi2", "Fysik1", "Fysik2", "Kemi1", "Kemi2", "Franska3", "Franska4", "Körsång1", "Körsång2"
        , "Gymnasiearbete"};

public void getInput(){
    for(int i = 0; i <= gradeName.length; i++){
        System.out.println("Enter grade for " + gradeName[i] + ": ");
        grade[i] = sc.nextLine();
    }


}
das-g
  • 9,718
  • 4
  • 38
  • 80
Tarmiac
  • 846
  • 1
  • 8
  • 14
  • 2
    Not the cause of the NullPointerException, but the last iteration will try to access `gradeName[gradeName.length]`, which is out of bounds because indexing is zero-based. Use `i < gradeName.length` (`<` instead of `<=`) or use an ['enhanced for-loop'](http://stackoverflow.com/a/11685345/674064) to iterate over all items. – das-g Sep 04 '15 at 13:26
  • 1
    Array's Index starts with `0` & ends with `length-1` – Subhrajyoti Majumder Sep 04 '15 at 14:14

2 Answers2

0

You are trying to use grade[] array before initializing it. Try

String grade[] = new String[gradeName.length] <br>

And in in your for loop for(int i = 0; i <= gradeName.length; i++)
In condition use only '<' instead of '<=' like this
for(int i = 0; i < gradeName.length; i++)
because 0 is the first index and size-1 is last index.

Kashyap Kansara
  • 405
  • 4
  • 10
0

It is very obvious, you have to allocate grade array first! In your constructor:

final int SIZE = 1024;
grade = new String[SIZE];

Actually i prefer to use an ArrayList instead of array in your case.

Alireza
  • 800
  • 1
  • 7
  • 21