Java 如何通过用户输入创建新的对象名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20359064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:21:12  来源:igfitidea点击:

How to create new object name by user input

javaobject

提问by user2879862

I want to create new object and to give it user input name.

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

Example user input "robert" wil match to:

示例用户输入“robert”将匹配到:

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

What do I need to change in the program so I can create a new object with a dynamic name? Many Thanks. I write the next code:

我需要在程序中更改什么才能创建具有动态名称的新对象?非常感谢。我写下一个代码:

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);

    }

}

采纳答案by Carlos N

Java, unlike other languages, does not have a way to dynamically create variable names. Variable names are declared in the code. In order to achieve what you're trying to do, look into the Collection's Map interface. This will allow you to "map" a user given name to some value.

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

Quick example:

快速示例:

//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.

更多信息在这里

回答by 4J41

Variable names cant be specified(created) at run time(dynamically).

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

回答by Amit Kumar user3037405

This is not possible. How can you declare the name of the Class object as a variable.

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