I'm writing a Lottery program where the user type sin 4 numbers between 1 and 30, the program generates 4 random numbers. In my program I have stored the random numbers and the numbers chosen by the player in 2 separate arrays. The problem I have is that I dont know how to make the program tell the user how many numbers they have matched.

Is there an easier way than writing so many if statements, is there a way of comparing the arrays? If anyone can help me I will be very grateful.

Mus.

Dani AI

Generated

's quick loop fixed the immediate problem for , but a few clarifications and cleaner options are useful if the program will be maintained or extended. Comparing arrays index-by-index only finds positional matches. For counting numbers that appear in both sets regardless of order, prefer a set intersection, a frequency map (if duplicates matter), or a sorted two-pointer scan.

Set intersection (counts distinct matches):

int[] player = { ... };
int[] drawn  = { ... };

Set<Integer> ps = new HashSet<>();
for (int n : player) ps.add(n);

Set<Integer> ds = new HashSet<>();
for (int n : drawn) ds.add(n);

ps.retainAll(ds);
int matches = ps.size(); // number of distinct matching values

Counting with multiplicity (handles duplicates properly):

Map<Integer,Integer> freq = new HashMap<>();
for (int n : drawn) freq.put(n, freq.getOrDefault(n,0) + 1);

int matches = 0;
for (int n : player) {
    Integer c = freq.get(n);
    if (c != null && c > 0) {
        matches++;
        freq.put(n, c - 1);
    }
}

Generating 4 unique random numbers from 1..30 (two common ways):

// shuffle pool (simple and uniform)
List<Integer> pool = IntStream.rangeClosed(1,30).boxed().collect(Collectors.toList());
Collections.shuffle(pool);
int[] drawn = pool.subList(0,4).stream().mapToInt(Integer::intValue).toArray();

// or use Random with a Set
Random rnd = new Random();
Set<Integer> drawnSet = new HashSet<>();
while (drawnSet.size() < 4) drawnSet.add(rnd.nextInt(30) + 1);

Final tips: validate player input (range 1..30 and no duplicates if that is a rule), reset counters between draws, avoid Arrays.asList on int[] (box to Integer[] or use streams), and pick the matching method that matches the intended rules (positional vs. unordered vs. multiplicity-aware).

A simple yet effective way to solve this would be to use a for loop to compare the elements of each array to the other using the for loop's variable. If they were equal, increment a counter variable (but don't forget to reset it after each use)

Thanks a lot for you help I used a for loop like you said and it works fine.

Mus

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.