简体   繁体   中英

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();
    }
  }

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.

It compiled. You defined a method setName before the constructor which doesn't affect the execution anyway. in the main method an instance of the class animal was created and on being created. the constrctor was called. And the code in the constructor is what asked for the name, Then the if statement checks if the user entered anything via the standard input. and passed the value to the setName method which in turn assigned the value to name.

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());
}

System.out.println("The name of the animal is: " + name);

}


public static void main(String[] args){

   animal Dog1 = new animal();
}
}

The code has various errors and doesn't compile. The user will be unable to input anything.

edit: Originally, the code didn't compile. Refer to above answers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM