user3725988 user3725988 - 7 months ago 17
Java Question

Need help on understanding user input in Java

Can someone explain the below code to me? Having a hard time understanding how the flow works. When the animal constructor is called in main(), it prints out "please input the name", but how does the user is able to input anything here? And how does it get assigned to the userInput? Lastly, why do we use this.setName(userInput.nextLine()) here?

import java.util.Scanner;
import java.util.*;

public class animal{

private String name;
static Scanner userInput = new Scanner(System.in);


public void setName(String name){
this.name = name;
}


public animal(){
System.out.println("please input the name");
if(userInput.hasNextLine()){

this.setName(userInput.nextLine());
}

}


public static void main(String[] args){

animal Dog1 = new animal();
}
}

Answer

When you run your program, the method:

userInput.hasNextLine()

Will block until the user type something and press enter (cf javadoc).

Once is done, you get the result from:

userInput.nextLine()

Then set the name of the dog with this value.

Finally, it returns the new animal instance with the name entered by the user.

Comments