How can I create my own variable with Java?

I would like to start with the fact that, if this is well known, please forgive me and show patience. I am a little new to Java. I am trying to write a program that will store many values ​​of variables in the form of a buffer. I was wondering if there is a way for the program to "create" its own variables and assign them to values. Here is an example of what I'm trying to avoid:

package test;

import java.util.Scanner;

public class Main {
     public static void main(String args[]) {

        int inputCacheNumber = 0;
        //Text File:
        String userInputCache1 = null;
        String userInputCache2 = null;
        String userInputCache3 = null;
        String userInputCache4 = null;

        //Program
        while (true) {
            Scanner scan = new Scanner(System.in);
            System.out.println("User Input: ");
            String userInput;
            userInput = scan.nextLine();

            // This would be in the text file
            if (inputCacheNumber == 0) {
                userInputCache1 = userInput;
                inputCacheNumber++;
                System.out.println(userInputCache1);
            } else if (inputCacheNumber == 1) {
                userInputCache2 = userInput;
                inputCacheNumber++;
            } else if (inputCacheNumber == 2) {
                userInputCache3 = userInput;
                inputCacheNumber++;
            } else if (inputCacheNumber == 3) {
                userInputCache4 = userInput;
                inputCacheNumber++;
            }
            // And so on

        }

    }
}

Therefore, to try to generalize, I would like to know if there is a way for a program to set an unlimited number of user input values ​​for String values. I am wondering if there is a way to avoid predefining all the variables that you might need. Thanks for reading, and your patience and help! ~ Rane

+4
1

Array List.

ArrayList AbstractList . ArrayList , .

:

List<String> userInputCache = new ArrayList<>();

,

if (inputCacheNumber == 0) {
    userInputCache.add(userInput); // <----- here
    inputCacheNumber++;
}

, :

for (int i = 0; i < userInputCache.size(); i++) {
    System.out.println(" your user input is " + userInputCache.get(i));
} 

enhanced for loop

for(String st : userInputCache) {
    System.out.println("Your user input is " + st);
}

. Scanner try catch block with resource, , .

:

try(Scanner input = new Scanner(System.in)) {
    /*
    **whatever code you have you put here**
    Good point for MadProgrammer:
    Just beware of it, that all. A lot of people have multiple stages in their   
    programs which may require them to create a new Scanner AFTER the try-block
    */
 } catch(Exception e) {
 }

ArrayList

http://www.tutorialspoint.com/java/java_arraylist_class.htm

+10

All Articles