0

I am writing a code which reads the following input

3
Ruby
Diamond
Sapphire

Here is my program

import java.util.Scanner;

public class GemStones {

    private int numOfStones;
    private String[] gemArray;

    public void solve() throws Exception{

        Scanner in = new Scanner(System.in);

        //Reading the integer
        numOfStones = Integer.parseInt(in.nextLine());
        //in.nextLine();
        System.out.println(numOfStones);


        //reading the strings
        for(int i=0;i<numOfStones;i++){
            gemArray[i] = in.nextLine();
            System.out.println(gemArray[i]);
        }


        for(int i=0;i<numOfStones;i++){
            System.out.println(gemArray[i]);
        }
        in.close();
    }


    public static void main(String[] args) throws Exception {
        GemStones check = new GemStones();
        check.solve();


    }

}

I have a problem reading the strings following it. Whenever I try to read the strings it shows me error! please help me..

The following is the error I get in the console

3
Ruby
Diamond
Sapphire3Exception in thread "main" 
java.lang.NullPointerException
    at com.sudarabisheck.easy.GemStones.solve(GemStones.java:23)
    at com.sudarabisheck.easy.GemStones.main(GemStones.java:37)

3 Answers3

1

The main problem is, once you've read the number of stones to be entered, you never initialise the gemArray before you use it...

numOfStones = Integer.parseInt(in.nextLine());
//in.nextLine();
System.out.println(numOfStones);

//reading the strings
for (int i = 0; i < numOfStones; i++) {
    gemArray[i] = in.nextLine();
    System.out.println(gemArray[i]);
}

You should use the numOfStones value to initialise the gemArray

numOfStones = Integer.parseInt(in.nextLine());
//in.nextLine();
System.out.println(numOfStones);

// Intialise gemStones here...
gemStones = new String[numOfStones];

//reading the strings
for (int i = 0; i < numOfStones; i++) {
    gemArray[i] = in.nextLine();
    System.out.println(gemArray[i]);
}
MadProgrammer
  • 323,026
  • 21
  • 204
  • 329
1

You never inizialize the array gmeArray so add the initialization:

public void solve() throws Exception{

            Scanner in = new Scanner(System.in);

            //Reading the integer
            numOfStones = Integer.parseInt(in.nextLine());
            //in.nextLine();
            System.out.println(numOfStones);

            gemArray = new String[numOfStones];
            //reading the strings
            for(int i=0;i<numOfStones;i++){
                gemArray[i] = in.nextLine();
                System.out.println(gemArray[i]);
            }


            for(int i=0;i<numOfStones;i++){
                System.out.println(gemArray[i]);
            }
            in.close();
        }
Jens
  • 60,806
  • 15
  • 81
  • 95
1

You need to initialize the Array as,

gemArray = new String[numOfStones];
Rakesh KR
  • 6,049
  • 5
  • 39
  • 49