Skip to content
Advertisement

I have a while loop and I want to call the variable multiple times is it possible?

An example of this would be

i = 0;
while(i < 3) {
Scanner scan = new Scanner();
String variableIWantToCallLater = scan.nextLine();
}

User enters macaroni the first time sausage the second time and cheese the third time.

Is there anyway that I could have store/save the first two times the user enters the input? Or would I have to use something else?

Advertisement

Answer

You can use array list to store all user inputs and use them later with something like this:

List<String> userInputs = new ArrayList<>();
Scanner scan = new Scanner(System.in);
for(int i=0; i<3; i++){
   System.out.println("Enter a text: ");
   String variableIWantToCallLater = scan.nextLine();
   userInputs.add(variableIWantToCallLater);
}
//userInputs in this case will be what u saved to use when the user is done entering the data.

Full implementation, tested and working

public class Test {
    private List<String> getInputs(){        
        List<String> userInputs = new ArrayList<>();
        Scanner scan = new Scanner(System.in);
        for(int i=0; i<3; i++){
           System.out.println("Enter a text: ");
           String variableIWantToCallLater = scan.nextLine();
           userInputs.add(variableIWantToCallLater);
        }
        return userInputs;
    }
    
    public static void main(String[] args) {
        System.out.println(new Test().getInputs());
    }
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement