简体   繁体   English

在理解Java用户输入方面需要帮助

[英]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? 当在main()中调用动物构造函数时,它会打印出“请输入名称”,但是用户如何在此处输入任何内容? And how does it get assigned to the userInput? 以及如何将其分配给userInput? Lastly, why do we use this.setName(userInput.nextLine()) here? 最后,为什么我们在这里使用this.setName(userInput.nextLine())?

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). 将阻塞,直到用户键入某些内容并按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. 您在构造函数之前定义了方法setName,该方法无论如何都不会影响执行。 in the main method an instance of the class animal was created and on being created. 在main方法中,创建了类动物的实例,并且在创建时。 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. 构造函数中的代码就是要求输入名称的代码,然后if语句检查用户是否通过标准输入输入了任何内容。 and passed the value to the setName method which in turn assigned the value to name. 并将值传递给setName方法,该方法又将该值分配给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. 请参考以上答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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