Sunday, July 6, 2014

Problem of nextInt and nextLine methods in Scanner class

Ever wondered why does nextInt() and nextLine() methods in java doesn't work properly when used simultaneously...Here you go..,

Let us say we have an object named input which is an instance of class Scanner.Now if you a code snipper lite the one below

var1=input.nextInt();
var2 = input.nextLine();
and if your input is say
1
hello
Now here var1 has the number 1 but the var2 doesn't have the string hello.this is because nextInt() method only takes input an Integer but it doesn't take the newline character "\n" so next thing in the input stream is new line character which will be saved into var2 when you now use a nextLine() method

How can we solve this Yah! the answer is below

method1:
You can insert a small snippet of code to remove that new line character from buffer i.e
var1=input.nextInt();
input.nextLine()
var2 = input.nextLine();

Method2:
Use two different objects of the class scanner call the method of first object when you use nextInt() method and use other second object for the nextLine() method..,this really works try it out!!!


No comments:

Post a Comment