2014-04-07 64 views
0

我将如何更改使用用户输入的对象的名称。前者为 。我要求用户输入他们的id作为一个字符串。 我想然后用它来创建一个构造函数。如何使用用户输入更改对象的名称?

例:

RefUnsortedList<Patients> NewList = new RefUnsortedList<Patients>(); 
Patients entry1=null; 
System.out.println("Please enter patient's ID: "); 
      String TargetID = scan.next(); 

我想设置

Patients entry1 = null; 

,使其

Patients "the user input here" = null; 
+0

我认为这不是一个良好的编程习惯。用户不应该命名变量。为此更好地创建一个属性。 – eventHandler

回答

1

没有动态变量在Java中,他们在被宣布源代码。

您可以尝试使用Map并为变量的每个实例分配一个键。

Map patientMap = new HashMap(); 
patientMap.put("entry1", new Patients()); 
patientMap.put("the user input here", new Patients()); 

然后,当你要检索的患者可以使用:

Patients patient = patientMap.get("the user input here"); 
1

你真正想要做的是:

Map<String, Patient> patients = new HashMap<>(); 
patients.put("entry1", /* [insert Patient object here] */); 

注意事项:

  • 代表患者的班级应命名为Patient,而不是Paitents。一个班级的名称应该是实例,而不是他们的集合

  • 是没有意义的地图中的值设置为null,除非您使用的是特殊类型的地图,允许null键(并使其从没有该键的条目有意义的不同)。

+0

Map类没有'.set'方法,它是'.put'来将对象添加到地图 –

+0

@MthetheWWilson谢谢,我误打错了。 – AJMansfield

+0

并且您在代码示例中错误输入了患者和患者。 –

0

我假设你正在做的事情是这样的:

你的病人类别:

public class Patient { 
    private String patientID; 

    public Patient(String patientID) { 
     this.patientID = patientID; 
    } 

    public String getPatientID() { 
     return patientID; 
    } 

    public void setPatientID(String patientID) { 
     this.patientID = patientID; 
    } 
} 

...和你的类,您正在使用运行控制台:

public class Main { 

    public Main() { 
    } 

    public static void main(String[] args) { 
     Scanner console = new Scanner(System.in); 
     System.out.println("System is ready to accept input, please enter ID : "); 
     String ID = console.nextLine(); 
     Patient patient = new Patient(ID); 
     //do some fancy stuff with your patient 
    } 

} 

这将是一个非常基本的例子。

当你正在学习编码时,一定要考虑如何命名你的类。调用你的类“患者”会让我期望你在这个java类的每个实例中都持有一组“患者”,而不是每个实例的单个“患者”。

关于最新的答案,包括地图,更新后的“主”类看起来是这样的:

public class Main { 
    static Map<String, Patient> patients = new HashMap<String, Patient>(); 

    public Main() { 
    } 

    public static void main(String[] args) { 
     Scanner console = new Scanner(System.in); 
     System.out.println("System is ready to accept input, please enter ID : "); 
     String id = console.nextLine(); 
     patients.put(id, new Patient(id)); 
    } 
}