m.T
m.T

Reputation: 51

problems with Scanner

I'm writing a java program that will take int input as a option from the user. Based on the input the program will go to different method.But when i run code it gives the following error

  Exception in thread "main" java.lang.NullPointerException
  at lab1.EchoClient.main(EchoClient.java:25)

part of my code

        private Scanner reader;
        public static void main(String[] args){

        EchoClient c = new EchoClient();
        int option;
        System.out.println("Welcome");
        System.out.println("Select one of the following options:");
        System.out.println("1 - Iterative Server");
        System.out.println("2 - Concurrent Server");
        System.out.println("3 - Exit");

        option = c.reader.nextInt(); // Line No 25
        switch(option){
        case 1: 
               c.iterative();//calls the iterative method
               break;
        case 2:
               //some method
               break;
        case 3:
               System.out.println ("bye bye");
               break;
        }//end of switch()
        }//end of main()

        public void iterative(){
               String address;
               String ip="";
               try{ 
                  System.out.println ("Please enter your correct ip address");
                  BufferedReader getip= new BufferedReader (newInputStreamReader(System.in));
                  ip=getip.readLine();
                  }
               catch (IOException error){
                   System.err.println("Error occured");
                }

At line 25 is the line : option = c.reader.nextInt();

Upvotes: 1

Views: 304

Answers (5)

Gabriel
Gabriel

Reputation: 3045

...did you define your private Scanner reader? Scanner reader = new Scanner(System.in);

Upvotes: 0

smp7d
smp7d

Reputation: 5032

reader is never initialised as far as I can tell

Upvotes: 0

jopasserat
jopasserat

Reputation: 5920

You need to build reader according to the instance you want to scan.

In your case this should look like:

Scanner reader = new Scanner(System.in);

Then, following your code snippet, you should set the reader owned by your instance of EchoClient to the built Scanner.

Upvotes: 2

Tim
Tim

Reputation: 60130

It looks like when you create your new EchoReader c, it doesn't set the reader attribute - then when you try c.reader, you get null, leading to the NPE when calling nextInt(). Double-check that your EchoReader constructor sets the reader attribute.

Upvotes: 0

duffymo
duffymo

Reputation: 308848

reader is never initialized, so it's still null.

Upvotes: 1

Related Questions