2013-12-03 62 views
1

我想创建新对象并为其提供用户输入名称。如何通过用户输入创建新对象名称

示例用户输入“罗伯特”西港岛线匹配:

Action robert = new Action(); 
robert.eat(); 

什么我需要在程序中改变这样我就可以创建新的对象与动态的名字吗? 非常感谢。 我写入下一个代码:

import java.util.Scanner; 

public class Human { 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     Scanner user_input = new Scanner(System.in); 

     String first_name; 
     System.out.print("Enter your first name: "); 
     first_name = user_input.next();//robert 

     System.out.println("You are " + first_name);//robert 

     Action first_name = new Action(); 
     Food orange = new Food(); 
     robert.eat(orange); 

    } 

} 
+0

对象通常不具有名称。你在谈论一个*变量*的名称,这是完全不同的。如果你希望你的对象有一个名字,它应该有一个字段来记住它的名字,你应该把这个名字传递给构造函数。 –

+0

你错了,YOu混合变量名和用户名! –

+0

如果没有人会在运行时看到它,为什么要给变量赋予一个动态名称? – Math

回答

1

与其他语言不同,Java不能动态创建变量名称。变量名称在代码中声明。为了实现你想要做的事情,请查看收藏的Map interface。这将允许您将给定名称的用户“映射”到某个值。

简单的例子:

//1) Setup the mapping, 
//The first parameter to put() is the key (perhaps a user given name?) 
//and the second parameter is actual value you want to map for that key. 
//note that although I'm using a String as the key and a String as the value 
//You can use pretty much any object as the value. Keys are recommended to be 
//immutable objects (a String is a good one) 
Map<String,String> mMap = new HashMap<String,String>(); 
mMap.put("John", "Orange"); 
mMap.put("Steve","Apple"); 

//2) Once the map is setup, you can then retrieve values given a key: 
System.out.println("John's fruit is: "+mMap.get("John")); 

More info here

+0

非常感谢。 – user2879862

0

变量名不能被指定(创建)在运行时(动态地)。

0

这是不可能的。如何将Class对象的名称声明为变量。

相关问题