Consider using a while-loop:
import java.util.Random;
class Sequence {
public static void main(String[] args) {
Random r = new Random();
int count = 0;
int num = -1;
System.out.println("The sequence is:");
while (num != 0) {
num = r.nextInt(10);
System.out.print(num + " ");
count++;
}
System.out.printf("%nThe length of the sequence is: %d%n", count);
}
}
Example Output:
The sequence is:
3 9 3 9 4 0
The length of the sequence is: 6
Alternatively if you need to store the sequence in a collection:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
class Sequence {
public static void main(String[] args) {
Random r = new Random();
List<Integer> result = new ArrayList<>();
int num = -1;
while (num != 0) {
num = r.nextInt(10);
result.add(num);
}
System.out.printf("The sequence is: %s%n", result);
System.out.printf("The length of the sequence is: %d%n", result.size());
}
}
solved Random Number generator in a range and then print length of the sequence [duplicate]