本文實例講述了java實現給出分數數組得到對應名次數組的方法。分享給大家供大家參考。具體實現方法如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
package test01; /** * 給出分數數組,得到對應的名次數組 * 列如有:score = {4,2,5,4} * 則輸出:rank = {2,3,1,2} */ import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ScoreRank { // 輸出數組 public static void show( int [] s){ for ( int x:s) System.out.print(x); System.out.println(); } // 取得名次 public static int [] scoreRank( int [] score) { int [] temp = new int [score.length]; List lis = new ArrayList(); for ( int x:score) // 添加元素(不重復) if (!lis.contains(x)) lis.add(x); Collections.sort(lis); // 從小到大排序 Collections.reverse(lis); // 從大到小排序 for ( int i= 0 ;i<score.length;i++) // 下標從 0 開始 temp[i] = lis.indexOf(score[i])+ 1 ; // 所以:正常名次 = 取得下標 + 1 return temp; } public static void main(String[] args){ int [] score = { 4 , 2 , 5 , 4 }; // 名次 {2,3,1,2} int [] rank = scoreRank(score); // 取得名次 System.out.print( "原始分數:" );show(score); System.out.print( "對應名次:" );show(rank); } } |
運行結果如下:
原始分數:4254
對應名次:2312
希望本文所述對大家的java程序設計有所幫助。