0

I am self teaching Java. While learning standard I/O I am keep getting following error.

Exception in thread "main" Enter first name : java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1371)
    at FirstJavaHello.ex_2_3(FirstJavaHello.java:46)
    at FirstJavaHello.main(FirstJavaHello.java:67)

Following is my code

import java.util.Scanner;

public class FirstJavaHello {

    public static void ex_2_1() {
        int radius = 2;
        double area;
        final double pi = 3.142;
        area= pi * radius * radius;
        System.out.printf ("The area is: %f", area);
        //System.out.println(area);
    }

    public static void ex_2_2() {
        int radius;
        double area, pi;
        Scanner readInput = new Scanner(System.in);
        //extra line feed
        System.out.println();

        System.out.printf("Enter the radius: ");
        radius = readInput.nextInt();
        //readInput.nextLine();

        Scanner readPI = new Scanner(System.in);
        //System.out.println();
        System.out.printf("Enter the PI: ");
        pi = readPI.nextDouble();
        //readPI.nextLine();

        area= pi * radius * radius;
        System.out.printf("The area is: %f", area);

        readPI.close();
        readInput.close();
    }


    public static void ex_2_3() {
        System.out.println();
        Scanner readStr = new Scanner(System.in);
        String firstName;

        System.out.printf("Enter first name : ");
        //readStr.nextLine();
        firstName = readStr.next();

        System.out.printf("your name is %s ", firstName);   
        readStr.close();
}

public static void main(String [] args) {
    ex_2_1();
    ex_2_2();
    ex_2_3();
}

}

Now if I comment ex_2_2() function call it works perfectly fine. I have read Javadoc and it says when there is no line next Scanner will throw exception. Can someone help to understand this concept little better.

Thanks

  • 2
    Don't create a second `Scanner`, use one `scanner` for all of your input. – Sergey Kalinichenko Mar 26 '18 at 18:47
  • I know it may look unrelated, but @dasblinkenlight is right. Closing the first `Scanner` object that wrapped `System.in` is the source of your problem. See the post linked above. – Bill the Lizard Mar 26 '18 at 18:53
  • Thank you for providing quick link. Since I am coming from C/C++ background obvious question won't it create resource leakage for the first Scanner? – Kartik Daiya Mar 26 '18 at 19:12

0 Answers0