0

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.

0

4 Answers 4

1

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);
 }
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Well, i did understand this but I want to know if it's possible to create a new variable instead of already having a variable precreated. This way I have to make a lot of variables to store all the users
1

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

Comments

0

I recomend using a Hashmap.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.