Lahori
Lahori

Reputation: 1091

Not getting user input as required in Java

I am new to java but not to programming as I know C++.

I am simply trying to get input from user either of integer or string form but when i execute my program, it just stands still and does nothing until I press enter. My program and result after pressing "Enter" is given.

My question is "why I am not getting user input?"

    import java.util.Scanner;

    class roomarea
    {
        public static void main(String[] args)
        {
            Scanner scanner = new Scanner(System.in);
            int input = scanner.nextInt();
            System.out.println("Enterd value is " + input);
        }
    }  

the result is

Start Running math >Command: "C:\Program Files\Java\jdk1.6.0\bin\java.exe"    
-classpath "C:\Documents and Settings\Ahmad Abdullah\My Documents\NaviCoder IDE for    
Java\projects\math\output\classes";"C:\Program Files\Java\jdk1.6.0\jre\lib\rt.jar";    
roomarea 

Exception in thread "main" java.util.InputMismatchException at
    java.util.Scanner.throwFor(Scanner.java:840)    at    
    java.util.Scanner.next(Scanner.java:1461)   at    
    java.util.Scanner.nextInt(Scanner.java:2091)    at    
    java.util.Scanner.nextInt(Scanner.java:2050)    at 
    roomarea.main(Main.java:14)  >Run

Process Completed

Upvotes: 0

Views: 157

Answers (2)

Maroun
Maroun

Reputation: 95948

Your program should work if you enter an int as input. (By pressing Enter while "waiting" for the program, you could arise the exception you're talking about).

If you enter a char for example, you'll get InputMismatchException exception:

Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.

Upvotes: 0

Quetzalcoatl
Quetzalcoatl

Reputation: 3067

When you say "it just stands still and does nothing untill i press enter", it is doing exactly what you told it to - it is waiting for you to input an int. You just hitting enter meant that there was no input, which your scanner could not interpret as an int, hence the exception.

If you enter an integer number then press the enter key, your program should work.

Upvotes: 2

Related Questions