java.util.Scanner offers an handy way to read the user input, but it's just as easy to use it incorrectly.
This is the first error:
Scanner sc = new Scanner(System.in); // Bad way of reading the input System.out.print("Type something:"); String line = sc.nextLine(); // The program waits here... System.out.println("You typed : " + line); sc.close();
This method doesn't allow to call hasNextInt() or hasNextDouble(), so we can't check for a particular input format, unless we use regular expressions.
In the attempt of fixing it, we can do a second error:
Scanner sc = new Scanner(System.in); // Bad way of reading the input System.out.print("Type a number:"); if(sc.hasNextInt()) { // Waits here... System.out.println("You typed : " + sc.nextInt()); } sc.close();
This method considers spaces as a delimiter, instead of considering as a single input what we type before pressing enter.
Finally we can do a third error:
Scanner sc = new Scanner(System.in); // Bad way of reading the input int num = 0; System.out.print("Type a number:"); if(sc.hasNextLine()) { // Waits here... num = Integer.parseInt(sc.nextLine()); System.out.println("You typed : " + num); } sc.close();
Here we get very easily a NumberFormatException.
The best way to read a user input is by using hasNextLine() followed by a type check with hasNextInt() or hasNextDouble(), in that way:
Scanner sc = new Scanner(System.in); // Correct way of reading the input System.out.print("Type a number:"); if(sc.hasNextLine()) { // Waits here... if (sc.hasNextInt()) // Don't wait here System.out.println("You typed the int : " + sc.nextInt()); else if (sc.hasNextDouble()) // Don't wait here System.out.println("You typed the double : " + sc.nextDouble()); else System.out.println("You typed the string : " + sc.next()); } sc.close();
Note also that you need to check for integers before than doubles.
Copyright © 2013 Welcome to the website of Davis Fiore. All Rights Reserved.