Java Arrays: Finding Unique Numbers In A Group of 10 Inputted Numbers

前端 未结 4 1764
离开以前
离开以前 2021-01-16 05:07

I\'m at a loss here.

I have this homework assignment where I have to enable the user to input 10 numbers, place them in an array, and figure out which inputted numbe

4条回答
  •  北恋
    北恋 (楼主)
    2021-01-16 05:44

    Check the numbers at they are entered, then keep track of which ones are unique by marking the same positions in a second (boolean) array with true if they are unique and false otherwise.

    Then, when you print out the unique values, only print the value from each position in numbers[] if that position in uniques[] contains true.

    Scanner input = new Scanner(System.in);
    int[] numbers = new int[10];
    boolean[] uniques = new boolean[10];
    
    for(int i = 0; i < 10; i++) {
        System.out.println("Please enter a value: \n" + "[" + (i + 1) + "]: ");
        numbers[i] = input.nextInt();
        uniques[i] = true;
        for(int j = 0; j < 10; j++) {
            if(numbers[i] == numbers[j] && i != j) {
                uniques[i] = false;
            }
        }
    }
    
    System.out.println("\nThe numbers you entered were: \n");
    for(int i = 0; i < 10; i++) {
        System.out.println(numbers[i] + ", ");
    }
    System.out.println("done.\n\n");
    
    System.out.println("\nThe uniqe numbers you entered were: \n");
    for(int i = 0; i < 10; i++) {
        if(uniques[i]) {
            System.out.println(numbers[i] + ", ");
        }
    }
    System.out.println("done.\n\n");
    

提交回复
热议问题