Java double for statement question.

Asked 2 years ago, Updated 2 years ago, 27 views

import java.util.Scanner; import java.util.Arrays;

public class test1 { public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    int[] num;
    num = new int[7];
    int[] num2 = new int[7];
    System.out.print("Please enter 6 numbers and 1 bonus number! :");
    for (int i = 0; i < num.length; i++) {
        num[i] = scan.nextInt();
        for (int j = 0; j < i; j++) {
            if (num[i] == num[j]) {
                i--;
                System.out.print ("Number is duplicated". Please re-enter! : ");
                break;
            }

        }
    }
    System.out.println(Arrays.toString(num));

    scan.close();
}

}

If you run the code above, you put a break, but you said, "The numbers are duplicated. Please re-enter! : The sentence " is printed 6 times and ends. I don't know what I'm missing. Please give us feedback.

java

2022-09-20 11:39

1 Answers

        for (int j = 0; j < i; j++) {
            if (num[i] == num[j]) {

The meaning of the above code is to compare all numbers in num[i] and num to see if they are the same.

If you put a value in num[i] in the upper line, num must have num[i] so that if must match once. So the number 6 is duplicated. Please re-enter! : will be printed.

To solve this problem, we can change if to exclude num[i] from the comparison, right?

            if (i != j && num[i] == num[j]) {


2022-09-20 11:39

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.