標籤:
一、程式題目:
三人行設計了一個灌水論壇。資訊學院的學生都喜歡在上面交流灌水,傳說在論壇上有一個“水王”,他不但喜歡發帖,還會回複其他ID發的每個文章。坊間風聞該“水王”發帖數目超過了貼文數目的一半。隨著論壇的發展,管理員發現水王沒有了,但是統計結果表明,有三個發帖很多的ID。據統計他們的發帖數量超過了1/4,如果你有一張當前論壇的文章(包括回帖)列表,其中文章的作者的ID也在其中,你能從發帖列表中快速找到他們嗎?
二、設計思想
從上一個尋找水王的思路來看,只需將計數器改為三個,利用兩個一維數組分別表示水王和計數器,在一次迴圈作者ID過程中,三個臨時水王分別與當前ID比較,得出三個水王。
三、代碼實現
import java.util.InputMismatchException;import java.util.Scanner;public class Finding_2 { public static void main(String[] args) { // TODO Auto-generated method stub for(;;) //按照使用者需求無限迴圈 { int judge=0; Scanner in=new Scanner(System.in); int n; System.out.println("請輸入文章的個數:"); n=in.nextInt(); System.out.println("請輸入ID(序號為正整數):"); int ID[]=new int [n]; try //捕捉輸入錯誤 { for(int i=0;i<n;i++) { ID[i]=in.nextInt(); } } catch(InputMismatchException e) { System.out.println("輸入不合法!請輸入整數!"); judge=1; } int shuiwang[]=new int [3]; int temp[]=new int[3]; //三個計數器,三個水王 temp[0]=temp[1]=temp[2]=0; shuiwang[0]=shuiwang[1]=shuiwang[2]=-1; //初始化計數器和三個水王ID for(int i=0;i<n;i++) { if(temp[0]==0) //如果temp為0,則水王換值為當前ID,計數器各加1 { temp[0]++; shuiwang[0]=ID[i]; } else if(temp[1]==0) { temp[1]++; shuiwang[1]=ID[i]; } else if(temp[2]==0) { temp[2]++; shuiwang[2]=ID[i]; } else if(ID[i]==shuiwang[0]) //當此時某水王與下一個ID相同時,計數器temp+1 { temp[0]++; } else if(ID[i]==shuiwang[1]) { temp[1]++; } else if(ID[i]==shuiwang[2]) { temp[2]++; } else //如果當前水王ID與當前ID都不同,則三個計數器都減一,直到temp為0 { temp[0]--; temp[1]--; temp[2]--; } } if(judge!=1) //如果沒有發生輸入錯誤,則找水王 { System.out.println("水王是:"); for(int i=0;i<3;i++) System.out.println(shuiwang[i]); } System.out.println("繼續尋找水王請按任意鍵,退出請按q:"); String s=in.next(); if(s.equals("q")) System.exit(0); else continue; in.close(); } }}
四、實現
五、個人總結
在前一個程式上的提高,要一步一步分析,鍛煉編程能力。
軟體工程個人作業06