編寫程式,讀取在1到100 之間的整數,然後計算每個數出現的次數。假定輸入是以0 結束的。 下麵是這個程式的一個運行示例: Write a program that reads the integers between 1and 100 and counts the occurrences of e ...
編寫程式,讀取在1到100 之間的整數,然後計算每個數出現的次數。假定輸入是以0 結束的。
下麵是這個程式的一個運行示例:
Write a program that reads the integers between 1and 100 and counts the occurrences of each. Assume the input ends with 0.Note that if a number occurs more than one time, the plural word “times” is used
in the output.
Enter the integers between 1 and 100: 2 5 6 5 4 3 23 43 2 0
2 occurs 2 times
3 occurs 1 time
4 occurs 1 time
5 occurs 2 times
6 occurs 1 time
23 occurs 1 time
43 occurs 1 time
下麵是參考答案代碼:
// https://cn.fankuiba.com
import java.util.Scanner;
public class Ans7_3_page236 {
public static void main(String[] args) {
int[] number = new int [101];
Scanner input = new Scanner(System.in);
int num;
System.out.print("Enter the integers between 1 and 100: ");
do {
num = input.nextInt();
number[num] = number[num] + 1;
}
while (num != 0);
for (int i = 1; i < number.length; i++) {
if (number[i] == 1) {
System.out.println(i + " occurs " + number[i] + " time");
}else if (number[i] > 1)
System.out.println(i + " occurs " + number[i] + " times");
}
}
}
適用Java語言程式設計與數據結構(基礎篇)(原書第11版)Java語言程式設計(基礎篇)(原書第10/11版)
發佈在博客:(https://cn.fankuiba.com)