1

Hi everyone I am still relatively new to Java and I was just wondering if anyone could help me with limiting the amount of times the user can input. As you can see right now the user can input unlimited times can anyone help me limit that to "n" times?

ArrayList<Integer> al = new ArrayList<Integer>();
int check=192;
while(true){
    check = input.nextInt();
    if(check == 192) break;
    al.add(check);
}

for (int i : al) {
    System.out.print(i);
}
3
  • This is an ArrayList, not an array. They can grow indefinitely (not really, but large enough). Arrays are of fixed-size. Commented Mar 21, 2017 at 18:49
  • You need a counter variable. Commented Mar 21, 2017 at 18:50
  • while(al.size() < N) Commented Mar 21, 2017 at 18:51

2 Answers 2

2

The easiest way is to declare counter before while loop and then increment counter after every input.

int count = 0;
int limit = x; // you declare how many times
while(true && count < x){
    // your code
    count++;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Why keeping the true condition in the while loop?
1
for(int i=0;i<N;i++){
   check = input.nextInt();
   al.add(check);
}

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.