編寫一個程式,讀人10 個數並且顯示互不相同的數(即一個數出現多次,但僅顯示一次)。(提示,讀人一個數,如果它是一個新數,則將它存儲在數組中。如果該數已經在數組中,則忽略它。)輸入之後,數組包含的都是不同的數。下麵是這個程式的運行示例: Write a program that reads in t ...
編寫一個程式,讀人10 個數並且顯示互不相同的數(即一個數出現多次,但僅顯示一次)。(提示,讀人一個數,如果它是一個新數,則將它存儲在數組中。如果該數已經在數組中,則忽略它。)輸入之後,數組包含的都是不同的數。下麵是這個程式的運行示例:
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版)
發佈在博客:(https://cn.fankuiba.com)