有没有办法从Java中的用户输入创建一个新变量

时间:2016-10-05 18:35:02

标签: java

我想创建一个用户数据库,它从控制台中输入的字符串创建一个新变量。我不知道这是否可能,我到处搜索。

4 个答案:

答案 0 :(得分:1)

当然,像这样:

// 1. Create a Scanner using the InputStream available.
Scanner scanner = new Scanner( System.in );

// 2. Don't forget to prompt the user
System.out.print( "Type some data for the program: " );

// 3. Use the Scanner to read a line of text from the user.
String input = scanner.nextLine();

// 4. Now, you can do anything with the input string that you need to.
// Like, output it to the user.
System.out.println( "input = " + input );

答案 1 :(得分:1)

有很多方法可以使用Reflection进行操作。但这会导致很多问题和设计问题。

相反,请尝试使用某种类型的键/值存储,以及这样的简单类:

public class KeyValueField
{
    public final String Key;
    public final String Value;

    public KeyValueField(String key, String value)
    {
        Key = key;
        Value = value;
    }
}

这样的用法:

System.out.print("Enter field name:");
String key= System.console().readLine();
System.out.print("Enter field value:");
String value = System.console().readLine();
KeyValueField newField = new KeyValueField(key, value);

答案 2 :(得分:1)

您可以使用List之类的数据结构,它可以容纳许多对象。向对象添加对象时,列表会增加。一个简单的入门列表是java.util.ArrayList

让您入门的示例:

 // create a new list which can hold String objects
 List<String> names = new ArrayList<>();
 String nextName = scanner.nextLine();

 // read names until the user types stop
 while(!nextName.equals("stop")) {
     // add new name to the list. note: the list grows automatically.
     names.add(nextName);
     // read next name from user input
     nextName = scanner.nextLine();
 }

 // print out all names.
 for(String name : names) {
     System.out.println(name);
 }

答案 3 :(得分:0)

我建议使用Hashmap。

import java.util.HashMap;
HashMap<String, String> keyValue = new HashMap<String, String>();
keyValue.put(key, value);
相关问题