简体   繁体   中英

How can I know what number is repeated?

I'm trying to know what number is repeated in Java.

I'm using 1.8JDK and never enter in IF. I don't know how can I do for program works, I'm hardstucked.

Can you check my code?

package exercici10;

import java.util.Scanner;

public class isRepeatedOrNot {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int[] myArray = new int[10];

        int[] myArray2 = new int[10];
        for (int i = 0; i < 10; i++) {
            myArray2[i] = myArray[i];
        }

        System.out.print("Enter 10 numbers: ");

        // Get myArray.
        for (int i = 0; i < 10; i++) {
            myArray[i] = sc.nextInt();
        }

        // Print myArray.
        for (int i = 0; i < myArray.length; i++) {
            for (int j = 0; j < myArray2.length; j++) {
                if (myArray[i] == myArray2[j]) {
                    System.out.println("Is repeated.");
                    return;
                }
            }
        }
        System.out.println("No numbers repeated.");

        sc.close();
    }
}

Thank you.

Regards, Alex.

You do not need to have two arrays, it is enough to use one array and a function that will check if there is a repetition of a number:

public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[] myArray = new int[10];

        System.out.print("Enter 10 numbers: ");

        // Get myArray.
        for (int i = 0; i < 10; i++) {
            myArray[i] = sc.nextInt();
        }

        
        System.out.println(isNumberRepeated(myArray));

        sc.close();
    }
    
    public static boolean isNumberRepeated(int[] array)
    {
        for (int i=0; i<array.length; i++) {
            for (int j=i+1; j<array.length; j++) {
                if (array[i]==array[j]) {
                    return true;
                    }
            }  
    }
        return false;
    }
}

Input :

Enter 10 numbers: 1
2
3
4
5
6
7
8
9
10
false

Input 2 :

Enter 10 numbers: 1
2
3
4
5
54
6
7
54
9
true

You could use HashSet which doesn't allow duplicate values.

public static void main(String[] args) {
    Integer[] myArray = {1, 2, 3, 1, 3, 4, 5, 7, 6, 3, 2};
    HashSet<Integer> uniqueNumbers = new HashSet<>();
    HashSet<Integer> repeatedNumbers = new HashSet<>();

    for (Integer integer : myArray) {
        if (uniqueNumbers.contains(integer)) {
            repeatedNumbers.add(integer);
        } else {
            uniqueNumbers.add(integer);
        }
    }
    System.out.println(repeatedNumbers);
}

Also if you need to modify your code to show number of times every number repeated, you could use hashmap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM