import?java.util.Arrays;
public?class?HelloWorld?{
????
????//完成?main?方法
????public?static?void?main(String[]?args)?{
?????int[]?scores={89,-23,64,91,119,52,73};??
?????HelloWorld?hello=new?HelloWorld();
?????hello.input(scores);
????}
????
????//定義方法完成成績排序并輸出前三名的功能
????public?void?input(int[]?scores)
????{
????????Arrays.sort(scores);
????????int?num=0;
?????????for(int?i=scores.length-1;i>=0;i--)
?????????{
?????????????if(scores[i]>0&&scores[i]<100)
????????????????num++;
?????????????if(num<3)
????????????????System.out.println(scores[i]);
?????????}
????}
}
要輸出三個(gè)成績呢??為啥我覺得應(yīng)該是num<=3,變量跟蹤也覺得是這樣啊
2015-08-05
你初始化的num=0 這 if判斷3次 ?num=0 ,1 , 2 就會輸出前3的成績 改成num<=3 則會輸出四個(gè)成績!
你可以初始化num=1 if(num<=3),這樣就是3個(gè)成績了!
2015-08-05
import java.util.Arrays;
public class HelloWorld {
? ? public static void main(String[] args) {
? ? ?int[] scores={89,-23,64,91,119,52,73}; ?
? ? ?HelloWorld hello=new HelloWorld();
? ? ?hello.input(scores);
? ? }
? public void input(int[] scores)?{
? ? ? ? Arrays.sort(scores);
? ? ? ? int num=0;
? ? ? ? ?for(int i=scores.length-1;i>=0;i--){
? ? ? ? ? ? ?if(scores[i]>0&&scores[i]<100){
? ? ? ? ? ? ? ? num++;
? ? ? ? ? ? ?if(num<=3)
? ? ? ? ? ? ? ? {System.out.println(scores[i]);}
????????????}
? ? ? ? ?}
? ? }
}
代碼改成這樣 兩個(gè)if 改成鑲嵌式 第一個(gè)if 成立時(shí)再執(zhí)行第二個(gè)if 就沒問題了
2015-08-05
不應(yīng)該是 判斷119時(shí) num+1=1;91時(shí)等于2;89時(shí)等于3嗎