Saturday 17 June 2017

java - How to get the right input for the String variable using scanner class?




I am learning Java and I was trying an input program. When I tried to input an integer and string using instance to Scanner class , there is an error by which I can't input string. When I input string first and int after, it works fine. When I use a different object to Scanner class it also works fine. But what's the problem in this method when I try to input int first and string next using same instance to Scanner class?




import java.util.Scanner;

public class Program {
public static void main(String[] args) {

Scanner input=new Scanner(System.in);

//Scanner input2=new Scanner(System.in);

System.out.println("Enter your number :" );


int ip = input.nextInt();

System.out.println("Your Number is : " + ip);

System.out.println("Enter Your Name : ");

String name= input.nextLine();

System.out.println("Your Next is : " + name);

}
}

Answer



nextInt() doesn't wait for the end of the line - it waits for the end of the token, which is any whitespace, by default. So for example, if you type in "27 Jon" on the first line with your current code, you'll get a value of 27 for ip and Jon for name.



If you actually want to consumer a complete line, you might be best off calling input.nextLine() for the number input as well, and then use Integer.parseInt to parse the line. Aside from anything else, that represents what you actually want to do - enter two lines of text, and parse the first as a number.



Personally I'm not a big fan of Scanner - it has a lot of gotchas like this. I'm sure it's fine when it's being used in exactly the way the designers intended, but it's not always easy to tell what that is.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...