在循环中发现数组中的唯一数字时遇到逻辑错误

问题描述 投票:0回答:2

这是我的Java类课本中的一个问题,用户输入10个整数。该程序应该读取所​​有整数,并且仅显示唯一数字(不重复)作为输出。

-运行时的输出为:输入10个数字:1 2 3 2 1 6 3 4 5 2不同数字的数量是5不同的数字是:1 2 3 0 0

-何时应为:输入10个数字:1 2 3 2 1 6 3 4 5 2不同数字的数量是5不同的数字是:1 2 3 6 4 5

由于我们处于课程的早期阶段,并且了解该语言,因此我们的任务是使用嵌套循环来完成此任务。任何帮助,将不胜感激。

import java.util.Scanner;

public class chapter7e5 {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        //create Scanner

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

        int[] numberArray = new int[10];
        //create array for all numbers

        int[] distinctArray = new int[10];
        //create array for distinct numbers

        int distinct = 0;

        for (int i = 0; i < 10; i++)
        //for loop to have user enter numbers and put them into array

            numberArray[i] = input.nextInt();

        distinctArray[0] = numberArray[0];
        //first value will be distinct

        for (int i = 1; i < numberArray.length; i++) {
        //loop to go through remaining values in numberArray

            boolean exists = false;
            //create boolean

            for (int j = 0; j < distinctArray.length; j++) {
            //loop to check if value exists already in distinctArray

                if (numberArray[i] == distinctArray[j]) {

                    exists = true;
                    //if value does already exists, then exist = true

                    break;
                    //break out of inner loop

                }
            }

            if (exists == false) {
            //if value is unique then add it to the distinct array

                distinctArray[i] = numberArray[i];

                distinct++;
                //increment variable distinct

            }
        }
        //}

        System.out.println("The number of distinct numbers is " + distinct);

        System.out.print("The distinct numbers are: ");

        for (int k = 0; k < distinct; k++)

            System.out.print(distinctArray[k] + " ");

    }

}
java
2个回答
0
投票

您使用了错误的变量作为索引来将值放入distinctArray[]

替换

distinctArray[i] = numberArray[i];
distinct++;

with

distinctArray[++distinct] = numberArray[i];

或者],您可以将其编写为:

distinct++;
distinctArray[distinct] = numberArray[i];

此更改后的示例运行:

Enter 10 numbers: 1 2 3 1 2 3 4 4 5 1
The number of distinct numbers is 4
The distinct numbers are: 1 2 3 4 

0
投票

我有以下建议:

© www.soinside.com 2019 - 2024. All rights reserved.