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