Basmeuw
Basmeuw

Reputation: 3

Is there a way to create a new variable from user input in Java

I want to make an user database, which creates a new variable from the string that was entered in the console. I don't know if this is possible and i've searched everywhere.

Upvotes: 0

Views: 1620

Answers (4)

Someone
Someone

Reputation: 1

I recomend using a Hashmap.

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

Upvotes: 0

Sky
Sky

Reputation: 709

You can use data structures like a List, which can hold a number of objects. A list grows when you add objects to them. A simple list to get started with is java.util.ArrayList.

Example to get you started:

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

Upvotes: 1

Silas Reinagel
Silas Reinagel

Reputation: 4203

There are ways to do what you asked using Reflection. But that leads to a lot of problems and design issues.

Instead, try using a Key/Value store of some sort, and a simple class like this:

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

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

Usage like this:

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

Upvotes: 1

David Cimbalista
David Cimbalista

Reputation: 15

Sure, like this:

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

Upvotes: 1

Related Questions