【问题标题】:How to create new object name by user input [duplicate]如何通过用户输入创建新的对象名称[重复]
【发布时间】:2013-12-04 03:50:22
【问题描述】:

我想创建新对象并给它用户输入名称。

示例用户输入“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);

    }

}

【问题讨论】:

  • 对象通常没有名字。你说的是一个变量的名字,这是完全不同的。如果你想让你的对象有一个名字,它应该有一个字段来记住它的名字,你应该把名字传递给构造函数。
  • 你错了,你把变量名和用户名混在一起了!
  • 如果没有人在运行时看到它,为什么要给变量一个动态名称?
  • 我感觉您正在寻找maps,它允许您使用可以是字符串的键来访问对象。

标签: java object


【解决方案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

【讨论】:

  • 非常有帮助,非常感谢。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-01
      • 2015-11-11
      • 1970-01-01
      相关资源
      最近更新 更多