Reputation: 47
My following code is mostly somebody else's, I was able to figure out how to print the correct range, but now I want to print that range (array) multiple times.
public class lottery {
public static void main(String[] args) {
int[] lottery = new int[6];
int randomNum;
for (int i = 0; i < 6; i++) {
randomNum = (int) Math.ceil(Math.random() * 59); // Random number created here.
for (int x = 0; x < i; x++) {
if (lottery[x] == randomNum) // Here, code checks if same random number generated before.
{
randomNum = (int) Math.ceil(Math.random() * 59);// If random number is same, another number generated.
x = -1; // restart the loop
}
}
lottery[i] = randomNum;
}
for (int i = 0; i < lottery.length; i++)
System.out.print(lottery[i] + " ");
}
}
The output, as expected is six integers in a row:
12 52 46 22 7 33
I have unfortunately not been able to find anything directly relevant to my question. I am an absolute Java beginner, so please be gentle.
The output I want is as follows, where each x is a random number.
x x x x x x
x x x x x x
x x x x x x
x x x x x x
x x x x x x
Technically, I'd like for the last number to be a random number, but a smaller range. I'll burn that bridge another time.
Upvotes: 0
Views: 2487
Reputation: 3570
Do you mean something like this?
for(int j = 0; j< numberOfTimeToPrint; j++)
{
for (int i = 0; i < lottery.length; i++)
System.out.print(lottery[i] + " ");
System.out.print("\n\n"); // 2 line feeds, 1 to terminate the line and another for a blank
}
Upvotes: 1
Reputation: 1954
Try it like this. You can use scanner to input the number of times yu require.
public class lottery {
public static void main(String[] args) {
int noTimes = 7;
for (int j = 0; j < noTimes; j++) {
int[] lottery = getRand();
for (int i = 0; i < lottery.length; i++) {
System.out.print(lottery[i] + " ");
}
System.out.println("\n");
}
}
public int[] getRand() {
int[] lottery = new int[6];
int randomNum;
for (int i = 0; i < 6; i++) {
randomNum = (int) Math.ceil(Math.random() * 59); // Random number created here.
for (int x = 0; x < i; x++) {
if (lottery[x] == randomNum) // Here, code checks if same random number generated before.
{
randomNum = (int) Math.ceil(Math.random() * 59);// If random number is same, another number generated.
x = -1; // restart the loop
}
}
lottery[i] = randomNum;
}
return lottery;
}
}
Upvotes: 0
Reputation: 13
for(int i = 0; i < lottery.length * howManyToPrint; i++){
System.out.print(lottery[i] + " ");
}
Upvotes: 0