Issue
I have a java lottery game assignment and where I am running a while loop to prevent duplication of numbers in the result.
I am getting a list of numbers with no duplicates, however the System.out.print
is returning all lines until I get the final one with no duplicates. Is there a way to only print the final "winning" line?
Code below
while (numCount<=9) {
int randNumber = rand.nextInt(99)+1;
if (results[0] == randNumber || results[1] == randNumber || results[2] == randNumber || results[3] == randNumber ||
results[4] == randNumber || results[5] == randNumber || results[6] == randNumber || results[7] == randNumber
|| results[8] == randNumber || results[9] == randNumber) {
} else {
Array.setInt(results, numCount, randNumber);
numCount++;
}
System.out.print("The Lottery Numbers are: ");
for (int i=0; i<10; i++)
//add a 0 in front of the number is it's less that 10
if (results[i] <10) {
System.out.print("0"+results[i]+" ");
}
}
Solution
You can do this simpler, relying on the fact that a Set
does not have duplicate objects in it.
public static void main(String[] args) {
Random rand = new Random();
Set<Integer> winningNumbers = new HashSet<>();
while (winningNumbers.size() < 9) {
int randNumber = rand.nextInt(99) + 1;
winningNumbers.add(randNumber);
}
System.out.print("The Lottery Numbers are: ");
for (Integer number : winningNumbers) {
//add a 0 in front of the number is it's less that 10
if (number < 10) {
System.out.print("0" + number + " ");
} else {
System.out.print(number + " ");
}
}
}
You can even simplify the way you are printing the numbers, relying on printf()
and %02d
, which means that 0 paddings are used being the maximum width of the printed numbers 2:
public static void main(String[] args) {
Random rand = new Random();
Set<Integer> winningNumbers = new HashSet<>();
while (winningNumbers.size() < 9) {
int randNumber = rand.nextInt(99) + 1;
winningNumbers.add(randNumber);
}
System.out.print("The Lottery Numbers are: ");
System.out.printf("%02d %02d %02d %02d %02d %02d %02d %02d %02d", winningNumbers.toArray());
}
In your code, just move the line System.out.print("The Lottery Numbers are: ");
to before the while loop and the loop for (int i=0; i<10; i++)
to after the while loop as follows:
System.out.print("The Lottery Numbers are: ");
while (numCount<=9) {
int randNumber = rand.nextInt(99)+1;
if (results[0] == randNumber || results[1] == randNumber || results[2] == randNumber || results[3] == randNumber ||
results[4] == randNumber || results[5] == randNumber || results[6] == randNumber || results[7] == randNumber
|| results[8] == randNumber || results[9] == randNumber) {
} else {
Array.setInt(results, numCount, randNumber);
numCount++;
}
}
for (int i=0; i<10; i++)
//add a 0 in front of the number is it's less that 10
if (results[i] <10) {
System.out.print("0"+results[i]+" ");
}
Answered By - João Dias
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.