There are two issues with your code:
- You are overriding the random number stored in
array[i]
with the statement, array[i] = i+1;
. You need to remove this statement.
- The condition,
if(array[i]%10==0)
will not give you line break after every 10
numbers because you are checking the value stored in the array instead of the loop counter. It should be if ((i + 1) % 10 == 0)
.
Also, you should initialize Random
outside of the loop.
Note: The way you have done will never give you unique random numbers. Note that your statement, rd.nextInt(100)+1
will give you an integer from 1
to 100
but when you execute this statement repeatedly, you may get same numbers repeated many times.
The easiest and fastest way I can think of is to initialize a list with integers from 1
to 100
, randomize the list and print the list in a 10x10 table as shown below:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
// Fill the list with integers from 1 to 100
for (int i = 1; i <= 100; i++) {
list.add(i);
}
// Shuffle the numbers in the list
Collections.shuffle(list);
// Display in a 10x10 table
for (int i = 0; i < 100; i++) {
System.out.printf("%4d", list.get(i));
if ((i + 1) % 10 == 0) {
System.out.println();
}
}
}
}
A sample run:
44 79 58 100 34 24 20 12 6 90
80 57 85 88 30 60 16 56 43 42
45 92 33 50 28 22 13 66 40 97
5 54 71 48 94 86 99 10 76 27
55 95 36 9 77 7 78 69 67 31
82 21 17 96 2 47 3 74 63 29
73 8 14 93 75 49 41 81 61 68
23 15 38 64 52 18 32 89 84 11
19 72 62 26 46 65 70 4 53 1
98 37 39 91 51 25 35 87 59 83