我想创建新对象并为其提供用户输入名称。
示例用户输入“robert”将匹配:
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 :(得分:1)
与其他语言不同,Java无法动态创建变量名称。变量名称在代码中声明。为了实现您想要做的事情,请查看Collection 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"));
答案 1 :(得分:0)
变量名不能在运行时指定(创建)(动态)。
答案 2 :(得分:0)
这是不可能的。如何将Class对象的名称声明为变量。