从java中的Object读取

时间:2014-04-29 09:22:42

标签: java object

Haj_Omra pr =new Promises( "Reem", 19,"10089", "italian","9/8/8" ,  " " );

//这里我要添加信息

但我希望用户从对象输入,我该怎么办? 我该如何使用扫描仪?

我试图将扫描仪放在课堂内,但它不起作用?

Class Check{
public void Sc(String ID){
Scanner input = new Scanner(System.in);
        System.out.print("Please enter a ID: ");
}

请任何想法??

2 个答案:

答案 0 :(得分:0)

哼..只需添加

String s = scan.nextLine();

在您声明扫描仪后获取用户条目,例如:

public void Sc(String ID){
    Scanner input = new Scanner(System.in);
    String s = scan.nextLine();
}

答案 1 :(得分:0)

通常,您不应直接访问对象的属性,应通过settergetter方法完成。因此,您应该使用所需的属性及其classsetter方法定义所需的getter。例如:

    public class MyClass
{
    private string myField; //"private" means access to this is restricted

    public string getMyField()
    {
         //include validation, logic, logging or whatever you like here
        return this.myField;
    }
    public void setMyField(string value)
    {
             //include more logic
             this.myField = value;
    }
}

引自:tutorial on getters and setters?

之后,您需要创建class的新对象,并通过setter方法设置其属性的值,其中值为用户输入。

MyClass myClassObj=new MyClass();   // creating new instance of MyClass 
System.out.println("Please enter an ID: ");
Scanner scan= new Scanner(System.in);
String userInput=scan.nextLine();   // get user input

myClassObj.setMyField(userInput);   // setting myFiled attribute 

仅用于测试目的,您可以通过myFiled方法获得getter值,如下所示:

System.out.println("The data enterd by user is: "+myClassObj.getMyFiled());