撰寫一個程式,讀人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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/149767.html
標籤:Java
