用帶參帶返回值不能完成這個嗎?
import java.util.Arrays;
public class HelloWorld {
? ? //完成 main 方法
? ? public static void main(String[] args) {
? ? ? ? System.out.println("考試成績的前三名:");
? ? ? ? int scores[] = {89, -23, 64, 91, 119, 52, 73};
? ? ? ? HelloWorld hello = new HelloWorld(); ? ?
? ? ? ? int b = hello.count(scores);
? ? ? ? System.out.println(b);
? ? ? ??
? ? }
? ??
? ? //定義方法完成成績排序并輸出前三名的功能
public int count(int scores[]){
? ? Arrays.sort(scores);
? ? int num = 0;
? ? for(int i = scores.length-1; i >= 0; i--){
? ? ? ? int a = 0;
? ? ? ? if(scores[i] > 100 || scores[i] < 0){
? ? ? ? ? ? continue;
? ? ? ? }
? ? ? ? a = scores[i];
? ? ? ? num++;
? ? ? ? if(num > 3){
? ? ? ? ? ? break;
? ? ? ? }
? ? ? ? return a;
? ? }
}
}
請問這樣錯在哪里呢
2017-06-14
用帶參帶返回值可以完成:
package test4;
import java.util.Arrays;
public class Test45 {
? ?//完成 main 方法
? ?public static void main(String[] args) {
? ? ? ?System.out.println("考試成績的前三名:");
? ? ? ?int scores[] = {89, -23, 64, 91, 119, 52, 73};
? ? ? ?Test45 hello = new Test45(); ? ?
? ? ? ?int[] b = hello.count(scores);//將返回值賦給數組b
? ? ? ?System.out.println(Arrays.toString(b));//用Arrays.toString方法輸出數組b的內容
? ?}
? ?//定義方法完成成績排序并輸出前三名的功能
public int[] count(int[] scores){//返回值類型應該為數組int[]
? ? ? ? int[] a = new int[3];//定義數組a的長度
? ?Arrays.sort(scores);//排序
? ?int num = 0;
? ?for(int i = scores.length-1; i >= 0; i--){
? ? ? ?if(scores[i] > 100 || scores[i] < 0){
? ? ? ? ? ?continue;
? ? ? ?}
? ? ? ?if(num >= 3){
? ? ? ? ? ?break;
? ? ? ?}else{//數組a賦值前三名的成績
? ? ? ? a[num] = scores[i];
? ? ? ? }
? ? ? ? ? ? num++;
? ?}
? ? ? ? return a;//返回數組a的內容
}
}
改動的地方都有注釋,可以看著理解一下
2017-06-11
你的數組聲明就有問題 ?應該是 int[] scores??= {89, -23, 64, 91, 119, 52, 73};吧 ?還有就是傳參 ?也應該是public int count(int[] scores)