Java

February 1, 2021

How do we take the input of a string after taking an integer as an input in Java?

To take input of a integer we use nextInt() function, that does not read the new line character of your input. So, when we command nextLine() it will take it as new line and give you as a new line. That’s why the nextLine() command after the nextInt() command gets skipped.

So when we code like, this:

Scanner scan = new Scanner ( System.in );

id = scan.nextInt();

name =scan.nextLine();

age = scan.nextInt();

System.out.println( i +” , ” + st + “ , ” + j );

In above part of code, when we try to give input the second input line would be skipped.

So we can the problem by doing it like this:

Scanner scan = new Scanner ( System.in );

id = scan.nextInt();

scan.nextLine();

name =scan.nextLine();

age = scan.nextInt();

System.out.println( i +” , ” + st + “ , ” + j );

Another way of doing this task could be:

Scanner scan = new Scanner ( System.in );

id = Integer.parseInt ( scan.nextLine() );

name = scan.nextLine();

age = scan.nextInt();

System.out.println( id +”,”+ name + “,” + age );

 

Scanner.next() :

If we would use next() function of Scanner class then only the first word would be considered as input, it would be a complete token in itself and next() takes the input of a single token only.

for eg:

name = scan.next();

System.out.println(“Name : “+ name);

Input:

Madan Mohan Malviya

Output:

Madan

But if we use nextLine() instead of next().

The Output would be,

Madan Mohan Malviya

by : Erfan Adil

Quick Summary:

To take input of a integer we use nextInt() function, that does not read the new line character of your input. So, when we command nextLine() it will take it as new line and give you as a new line. That’s why the nextLine() command after the nextInt() command gets skipped. So when we code […]