public class HelloWorld {? ??? ? //完成 main 方法? ? public static void main(String[] args) {? ? ? ? int [] scores={89,-23,64,91,119,52,73};? ? ? ? HelloWorld hello=new HelloWorld();? ? ? ? hello.sco(scores);? ? ? ??? ? }? ??? ? //定義方法完成成績排序并輸出前三名的功能? ??? ? public void sco(int scores[]){? ? ? ? int score,i,j;? ? ? ? for(i=0;i<scores.length-1;i++){? ? ? ? ? ? for(j=i;j<scores.length;j++){? ? ? ? ? ? ? ? if(scores[j]>scores[i]){? ? ? ? ? ? ? ? ? ? score=scores[i];? ? ? ? ? ? ? ? ? ? scores[i]=scores[j];? ? ? ? ? ? ? ? ? ? scores[j]=score;? ? ? ? ? ? ? ? }? ? ? ? ? ? }? ? ? ? }? ? ? ? System.out.println("前三名為:");? ? ? ? for(i=0,j=0;j<3;i++){? ? ? ? if(scores[i]>=0&&scores[i]<=100){? ? ? ? ? ? ?System.out.println(scores[i]);? ? ? ? ? ? ?j++;? ? ? ? }? ? ? ? }? ? }? ??? ??? ??? ??? ??}//下面的為什么不可以?/*public class HelloWorld {? ??? ? //完成 main 方法? ? public static void main(String[] args) {? ? ? ? int [] scores={89,-23,64,91,119,52,73};? ? ? ? HelloWorld hello=new HelloWorld();? ? ? ? hello.sco(scores);? ? ? ??? ? }? ??? ? //定義方法完成成績排序并輸出前三名的功能? ??? ? public void sco(int scores[]){? ? ? ? int score;//就只是把i,j的聲明放在了for循環(huán)里面,進行編譯就報錯,大概是說第二個for里不能使用i,j,為什么? ? ? ? for(int i=0;i<scores.length-1;i++){? ? ? ? ? ? for(int j=i;j<scores.length;j++){? ? ? ? ? ? ? ? if(scores[j]>scores[i]){? ? ? ? ? ? ? ? ? ? score=scores[i];? ? ? ? ? ? ? ? ? ? scores[i]=scores[j];? ? ? ? ? ? ? ? ? ? scores[j]=score;? ? ? ? ? ? ? ? }? ? ? ? ? ? }? ? ? ? }? ? ? ? System.out.println("前三名為:");? ? ? ? for(i=0,j=0;j<3;i++){? ? ? ? if(scores[i]>=0&&scores[i]<=100){? ? ? ? ? ? ?System.out.println(scores[i]);? ? ? ? ? ? ?j++;? ? ? ? }? ? ? ? }? ? }? ??? ??? ??? ??? ??}*/
2 回答
已采納

Caballarii
TA貢獻1123條經(jīng)驗 獲得超629個贊
如果在for循環(huán)的括號里定義int i,int j,那么i和j的作用域就只在這個循環(huán)內(nèi),循環(huán)外是不可以用的,所以你第二個for循環(huán)里也得寫成int i=0。建議不同的循環(huán)里使用不同的循環(huán)變量,否則容易沖突出錯
添加回答
舉報
0/150
提交
取消