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

Scope of If-statement

if is a conditional statement, which returns true or false based on the condition that is passed in it’s expression.

By default, if-statement is implemented on only one line, that follows it.
But if we put block after the if-statement, it will be implemented on the whole block.

Syntax_1:
if(expression)
statement

In the above example, if-statement will be implemented on only statement.

Syntax_2:
if(expression)
{
statement1
statement2
…………….
}

In above example, if-statement will be implemented on the whole block, to all the statements that would be present there.

Note: Same happens with else too.