編寫一個 JAVA 程序,實現輸出考試成績的前三名
要求:
1、 考試成績已保存在數組 scores 中,數組元素依次爲 89 , -23 , 64 , 91 , 119 , 52 , 73
2、 要求通過自定義方法來實現成績排名並輸出操作,將成績數組作爲參數傳入
3、 要求判斷成績的有效性( 0—100 ),如果成績無效,則忽略此成績
package Arrays;
import java.util.Arrays;
public class ArraysText {
public static void main(String[] args)
{
int[] scores = new int[]{89,-23,64,91,119,52,73};
ArraysText hello = new ArraysText();
int[] fi = hello.arrays(scores);
System.out.println("考試成績前三名爲"+Arrays.toString(fi));
}
//定義一個方法實現數組的輸入和判斷輸出成績前三名
public int[] arrays(int[] scores)
{
int[] newScores = new int[100];
int j = 0;
for(int i = 0;i <scores.length;i++)//循環遍歷數組判斷數組元素的有效性
{
if(scores[i] > 0 && scores[i] < 100)
{
newScores[j] = scores[i];//如果有效賦值給一個新的數組
j++;
}
}
Arrays.sort(newScores);//對數組由小到大進行排序
int[] host = new int[3];//定義一個新的數組用於存儲前三名的成績
int num = newScores.length;
for(int p = 0;p <3;p++)//通過遍歷將前三名成績輸入到host[]數組中
{
host[p] = newScores[num-(p+1)];
}
return host;
}
}