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.
4 Answers
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);
}
Comments
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
Basmeuw
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
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);