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