第七章第五題(打印不一樣的教)(Print distinct numbers) - 編程練習題答案

編寫一個程序,讀人10 個數而且顯示互不相同的數(即一個數出現屢次,但僅顯示一次)。(提示,讀人一個數,若是它是一個新數,則將它存儲在數組中。若是該數已經在數組中,則忽略它。)輸入以後,數組包含的都是不一樣的數。下面是這個程序的運行示例:java

Write a program that reads in ten numbers and displays
the number of distinct numbers and the distinct numbers separated by exactly one
space (i.e., if a number appears multiple times, it is displayed only once). (Hint:
Read a number and store it to an array if it is new. If the number is already in the
array, ignore it.) After the input, the array contains the distinct numbers.數組

下面是參考答案代碼:數據結構

// https://cn.fankuiba.com
import java.util.Arrays;
import java.util.Scanner;

public class Ans7_5_page236 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter ten numbers: ");
        int[] numberList = new int[10];
        // int[] distinctList = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
        int[] distinctList = new int[10];
        Arrays.fill(distinctList,-1);

        for (int i = 0; i < 10; i++)
            numberList[i] = input.nextInt();

        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10;j++) {
                if (i == numberList[j])
                    distinctList[i] = numberList[j];
            }
        }

        int count = 0;
        for (int i = 0; i < 10; i++) {
            if (distinctList[i] != -1)
                count++;
        }
        System.out.print("The number of distinct number is " + count+
                "\nThe distinct numbers are: ");

        for (int i = 0; i < 10; i++) {
            if (distinctList[i] != -1) {
                System.out.print(distinctList[i] + " ");
            }
        }
    }
}

適用Java語言程序設計與數據結構(基礎篇)(原書第11版)Java語言程序設計(基礎篇)(原書第10/11版)app

發佈在博客:(https://cn.fankuiba.com)ui

相關文章
相關標籤/搜索