读取十个数字的程序,显示不同数字的数量和由一个空格分隔的不同数字

时间:2017-03-16 04:37:19

标签: java eclipse

我知道之前已经问过这个问题,但不是我编写代码的格式。刚刚开始学习java类,所以我不熟悉任何复杂的java ..下面的代码包括基本上我知道的所有java。请帮忙!提前致谢。

import java.util.Scanner;
public class problem2try {

    public static void main(String[] args) {
        //declarations 
        Scanner keyboard = new Scanner (System.in);  
        int [] inputList = new int [10]; 
        int [] distinctArray = new int [10]; 
        int num; 
        int counter = 0; 

        //input 
        System.out.print("Please enter in 10 integers: ");

        for (int i = 0; i < inputList.length; i++)
        {
            num = keyboard.nextInt(); 
            inputList[i] = num; 
        }

        //processing
        distinctArray[0] = inputList[0]; 
        for (int i = 1; i < inputList.length; i++)
        {
            for (int j = 0; j < inputList.length; j++)
            {
                if (inputList[i] == inputList[j])
                {
                    counter++; 
                    continue; 
                }
                else
                {
                    distinctArray[i] = inputList[i];
                }
            }
        }

        //output
        System.out.println("The number of distinct numbers is " + counter);
        System.out.print("The distict numbers are: ");
        for (int x=0; x<distinctArray.length; x++)
        {
            if (distinctArray[x] != 0)

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

1 个答案:

答案 0 :(得分:1)

您在“处理”块中的逻辑似乎已关闭。我修改它以检查所有已知数字(内循环)的当前数字(外循环)。如果未找到匹配项,则会将其附加到已知数字列表中,并且计数会递增。

我还修改了“输出”代码,以便从已知数字列表中打印出第一个counter数字。超过该索引的值未初始化。

import java.util.Scanner;
public class problem2try {

    public static void main(String[] args) {
        //declarations 
        Scanner keyboard = new Scanner (System.in);  
        int [] inputList = new int [10]; 
        int [] distinctArray = new int [10]; 
        int num; 
        int counter = 0; 

        //input 
        System.out.print("Please enter in 10 integers: ");

        for (int i = 0; i < inputList.length; i++)
        {
            num = keyboard.nextInt(); 
            inputList[i] = num; 
        }

        //processing
        for (int i = 0; i < inputList.length; i++)
        {
            boolean found = false;
            for (int j = 0; j < counter; j++)
            {
                if (inputList[i] == distinctArray[j])
                {
                    found = true;
                    break;
                }
            }
            if (!found)
            {
                distinctArray[counter++] = inputList[i];
            }
        }

        //output
        System.out.println("The number of distinct numbers is " + counter);
        System.out.print("The distict numbers are: ");
        for (int x=0; x<counter; x++)
        {
            System.out.print(distinctArray[x] + " ");
        }
    }
}