標籤:java 小項目 排序
最近在看基礎的java教程,發現java很多與c++類似,但也有不少差異,有很多要注意的地方,做了這個成績管理系統,還沒用到類,只是多維陣列的應用。
期間遇到很多問題,也都經過一一百度解決了。
實現的功能: 輸入學生人數,以及學生考試的科目數,然後依次填入資訊,最後輸出學生資訊,以及總分,平均分,名次;
import java.util.*;import java.math.*;import java.text.*;//引入控制格式的包,import java.text.DecimalFormat; 用來控制浮點數小數位元public class Test{public static void main(String[] args){Scanner in=new Scanner(System.in);System.out.println("請輸入一共有幾門課程");int numberofCoarses=in.nextInt();System.out.println("請輸入一共有幾個學生");int numberofStudents=in.nextInt();System.out.println("請定義這幾門課程");String [] coarse=new String[numberofCoarses];String [] name=new String[numberofStudents];for(int i=0;i<numberofCoarses;i++)coarse[i]=in.next();double[][] stuu =new double[numberofStudents][numberofCoarses];double[] totalGrades=new double [numberofStudents];double[] average=new double [numberofStudents];double[] totalsort=new double [numberofStudents];int[] paihang = new int [numberofStudents];DecimalFormat df=new DecimalFormat("0.00");//設定浮點數的位元for(int i=0;i<numberofStudents;i++){System.out.println("請輸入第"+(i+1)+"個學生的名字");name[i]=in.next();System.out.println("請依次輸入"+name[i]+"的"+numberofCoarses+"門成績");double sum=0;for(int j=0;j<numberofCoarses;j++){stuu[i][j]=in.nextDouble();sum+=stuu[i][j];}totalGrades[i]=sum;average[i]=sum/numberofCoarses;}//totalsort=totalGrades 錯誤,淺複製,指向同一個引用;//totalsort=totalGrades.clone(); //數組的深複製//用clone只能複製一維數組,多維陣列需要加上for迴圈依次cloneSystem.arraycopy(totalGrades,0,totalsort,0,totalGrades.length); //最快的賦值 //第一個0,代表源數組賦值的起始位置,第二個0,代表被賦值數組的起始位置 for(int i=0;i<totalsort.length-1;i++) //選擇排序{int k=i;for(int j=i+1;j<totalsort.length;j++){if(totalsort[j]>totalsort[k]){k=j;}}if(k!=i){double temp=totalsort[k];totalsort[k]=totalsort[i];totalsort[i]=temp;}} //Arrays.sort(totalsort,Collections.reverseOrder()); << 有錯誤,改天再看看庫函數怎麼排序吧。。for(int i=0;i<paihang.length;i++) //二分尋找{int head=0,tail=paihang.length-1;while(head<=tail){if(totalsort[head]==totalGrades[i]){paihang[i]=head+1;break; }else if(totalsort[tail]==totalGrades[i]){paihang[i]=tail+1;break;}else{int mid=(head+tail)/2;if(totalsort[mid]==totalGrades[i]){paihang[i]=mid+1;break;}else if(totalsort[mid]>totalGrades[i]){tail=mid-1;}elsehead=mid+1;}}}System.out.print("學生\t");for(int i=0;i<numberofCoarses;i++)System.out.print(coarse[i]+"\t");System.out.println("總分\t平均分\t熱門排行榜");for(int i=0;i<numberofStudents;i++){System.out.print(name[i]+"\t");for(int j=0;j<stuu[i].length;j++){System.out.print(stuu[i][j]+"\t");}System.out.print(totalGrades[i]+"\t");System.out.print(df.format(average[i])+"\t");System.out.print("第"+paihang[i]+"名");System.out.println();}}}
學產生績管理系統(java實現)