0

I am trying to understand gathering user input and looping until conditions. I want to loop a scanner until user inputs 0, however, I need each inputted integer to be stored so it can be accessed for later use. The hard part is, I can't use an array.

user247702
  • 23,641
  • 15
  • 110
  • 157
Ryan
  • 57
  • 1
  • 5
  • 15

3 Answers3

0

simply you can do something like

List mylist = new ArrayList(); //in java. other wise you can create array[size]
int input = 1;
while(input!=0)
{
  /* input number from user here */

  if(input!=0)
  mylist.add(input);

}
Zeeshan
  • 2,884
  • 3
  • 28
  • 47
0

Here is an easy way to loop user input until 0 is entered.

Scanner console = new Scanner(System.in);
boolean loop = true;
String input;
while(loop) {
    input = console.nextLine();
    //Add input to a data structure
    if (input.equals("0")) {
        loop = false;
    }
}

As far as adding the user input to a data structure, you said you can't use an Array. How about a List or a Set. Even a Stack or a Queue would work. Have you looked at using any of these data structures?

Here is a basic example using a List:

List<String> aList = new ArrayList<String>();
aList.add(input);

And this is how you might use a Stack:

Stack<String> stk = new Stack<String>();
stk.push(input);

Perhaps the most efficient way would be to use a HashSet:

Set<String> set = new HashSet<String>();
set.add(input);
ElliotSchmelliot
  • 7,322
  • 4
  • 41
  • 64
0

Using arrays here would be little tricky since you don't know the numbe of elements user is going to enter. You can always write the code to create a new array with bigger capacity once user has exhaused initial capacity and copy over existing input elements but using List would be much easier.

    Scanner scanner = new Scanner(System.in);

    List<Integer> input = new ArrayList<>();
    int nextInt = Integer.MIN_VALUE;
    while((nextInt = scanner.nextInt()) != 0){
        input.add(nextInt);
    }

See this question if you really want to use arrays. Answer explains on creating new arrays and copying over elements. Java dynamic array sizes?

Community
  • 1
  • 1
RandomQuestion
  • 6,778
  • 17
  • 61
  • 97