Java黑皮书课后题第7章:**7.3(计算数字的出现次数)编写程序,读取1到100之间的整数,然后计算每个数出现的次数。假定输入0表示结束
生活随笔
收集整理的這篇文章主要介紹了
Java黑皮书课后题第7章:**7.3(计算数字的出现次数)编写程序,读取1到100之间的整数,然后计算每个数出现的次数。假定输入0表示结束
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
7.3(計(jì)算數(shù)字的出現(xiàn)次數(shù))編寫程序,讀取1到100之間的整數(shù),然后計(jì)算每個數(shù)出現(xiàn)的次數(shù)
- 題目
- 題目描述+運(yùn)行示例
- 破題
- 法一
- 法二
- 代碼
- 法一:硬生生解出來
- 法二完整代碼
題目
題目描述+運(yùn)行示例
**7.3(計(jì)算數(shù)字的出現(xiàn)次數(shù))編寫程序,讀取1到100之間的整數(shù),然后計(jì)算每個數(shù)出現(xiàn)的次數(shù)。輸入0表示結(jié)束
如果一個數(shù)出現(xiàn)的次數(shù)大于1次,就在輸出時使用復(fù)數(shù)times
下面是一個運(yùn)行示例:
破題
法一
法二
基本思想:
這個時候下標(biāo)數(shù)=用戶輸入的整數(shù),而lst[下標(biāo)數(shù)] = 下標(biāo)數(shù)出現(xiàn)的次數(shù)
2. 將lst1數(shù)組遍歷一邊,下標(biāo)index即輸出的數(shù)字、lst[index]即這個數(shù)字出現(xiàn)的次數(shù),對lst[index]分三種情況討論輸出即可
代碼
法一:硬生生解出來
import java.util.Arrays; import java.util.Scanner;public class Test7_3 {public static void main(String[] args) {//1. 聲明一個數(shù)組lst_inputint[] lst_input = new int[101];//2. 讀取整數(shù),判斷是否符合“0到100之間的整數(shù)”標(biāo)準(zhǔn),如果不符合則丟棄繼續(xù)讀取,如果讀到0則結(jié)束讀取Scanner input = new Scanner(System.in);int count0 = 0;System.out.print("Enter the integer between 1 and 100:");int temp = -1;for (int i = 0;;i++){temp = input.nextInt();// 判斷是否在0~100之間if (temp >= 0 && temp <= 100){if (temp == 0) {break;}else{lst_input[i] = temp;count0++;}} else{System.out.println("不符合要求的輸入,程序即將退出");System.exit(1);}}// 取lst_input的前count個數(shù)賦值給lstint[] lst = new int[count0];for (int i = 0; i < count0; i++)lst[i] = lst_input[i];//3. 對數(shù)組進(jìn)行排序Arrays.sort(lst)Arrays.sort(lst);//4. 對數(shù)組進(jìn)行遍歷,計(jì)算每個數(shù)出現(xiàn)的次數(shù)并輸出int length = lst.length, count = 0, temp1 = 0;for (int i = 0; i < length;i++){//temp1保存相同元素,count計(jì)算次數(shù)//三種情況:i=0、temp1值=lst[i]、temp1值≠lst[i]if (i == 0){temp1 = lst[i];count = 1;continue; // 跳出本輪次循環(huán),i自增1、判斷條件是否成立,并進(jìn)入下一輪循環(huán)}if (temp1 != lst[i]){if (count > 1) {System.out.println(temp1 + " occurs " + count + " times");}else {System.out.println(temp1 + " occurs " + count + " time");}temp1 = lst[i];count = 1;}else{count++;}}// 輸出最后一個元素的結(jié)果if (count > 1) {System.out.println(temp1 + " occurs " + count + " times");}else{System.out.println(temp1 + " occurs " + count + " time");}} }法二完整代碼
import java.util.Scanner;public class Test7_3 {public static void main(String[] args) {int[] lst1 = new int[101];int n = -1;Scanner input = new Scanner(System.in);System.out.print("Enter the integers between 1 and 100: ");do{n = input.nextInt();++lst1[n];}while(n != 0);for (int i = 1; i < 101;i++){if (lst1[i] == 0){continue;}else if (lst1[i] == 1){System.out.println(i + " occurs " + lst1[i] + " time");} elseSystem.out.println(i + " occurs " + lst1[i] + " times");}} }總結(jié)
以上是生活随笔為你收集整理的Java黑皮书课后题第7章:**7.3(计算数字的出现次数)编写程序,读取1到100之间的整数,然后计算每个数出现的次数。假定输入0表示结束的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java黑皮书课后题第7章:7.2(倒置
- 下一篇: Java黑皮书课后题第7章:7.4(分析