Java Scanner read input from console

Question

What is the output if you input 5a when running the following code:

import java.util.Scanner; // Scanner is in the java.util package

public class Main {
  public static void main(String[] args) {
    final double PI = 3.14159; // Declare a constant
    //from  w w  w . j a v a  2 s. com
    // Create a Scanner object
    Scanner input = new Scanner(System.in);
    
    // Prompt the user to enter a radius
    System.out.print("Enter a number for radius: ");
    double radius = input.nextDouble();

    // Compute area
    double area = radius * radius * PI;

    // Display result
    System.out.println("The area for the circle of radius " +
      radius + " is " + area);
  } 
}


Enter a number for radius: 5a
Exception in thread "main" java.util.InputMismatchException
  at java.util.Scanner.throwFor(Scanner.java:864)
  at java.util.Scanner.next(Scanner.java:1485)
  at java.util.Scanner.nextDouble(Scanner.java:2413)
  at Main.main(Main.java:12)

Note

5a is not a double type input so the code stopped with error.




PreviousNext

Related