I need help understanding how to write a for loop that takes in a certain amount of integers (must be 1 through 10) and it stops taking in numbers once 0 is entered (0 will be the last number). My code so far is:
import java.util.Scanner;
public class countNum {
public static void main(String[] args) {
int[] array;
Scanner input = new Scanner(System.in);
System.out.println ("Enter in numbers (1-10) enter 0 when finished:");
int x = input.nextInt();
while (x != 0) {
if (x > 2 && x < 10) {
//Don't know what to put here to make array[] take in the values
}
else
//Can I just put break? How do I get it to go back to the top of the while loop?
}
}
}
}
I don’t understand how to simultaneously initialize an array with a set length while having the Scanner read a certain amount of digits of that unknown length, until 0 is entered, and then the loop stops taking in input for the array.
Thanks for any help!
Ok here’s the bit more detail: –
You need to use an
ArrayListif you want a dynamically increasing array. You do it like this: –Now, in your above code, you can put your
numberreading statement (nextInt) inside the while loop, since you want to read it regularly. And put a condition in while loop to check whether the entered number is an int or not: –Further, you can move on your own. Just check whether the number is
0or not. If it is not0, then add it toArrayList: –If its
0, break out of your while loop.And you don’t need that
x != 0condition in your while loop, as you are already checking it inside the loop.