以這樣的程序,如何輸出前三名。
public static void main(String[] args) {?
? ? HelloWord hello=new HelloWord();
? ? hello.score();
}
public void score() {
int max=0;
int[] score= {89,-23,64,91,119,52,73};
for(int i=0;i<score.length;i++){
if(score[i]>=0 && score[i]<=100) {
if(max < score[i]) {
max=score[i];
}
}
}
System.out.println("考試成績(jī)的前三名為:");
for(int x=0;x<3;x++) {
System.out.println(max);
}
}
}
2018-10-07
還有一種方法 改前面的for循環(huán)
代碼如下:
public void score() {
int max=0;
int[] max=new int[3];? //取前3,因此數(shù)組長(zhǎng)度為3
int count=0;? //該變量代表有效值次數(shù)
int[] score= {89,-23,64,91,119,52,73};
Arrays.sort(score); // 給數(shù)組score從低到高排序,第一行上邊要有import??java.util.Arrays;
for(int i=0;i<score.length;i++){
if(score[i]>=0 && score[i]<=100) {
if(max < score[i]) {
max=score[i];
}
改為:
if(score[i]<0||score[i]>100){
continue;
}? ? ?//跳過無效值
count++;? //遍歷一個(gè)有效值,有效值次數(shù)加1?
if(count>=3){
break;
}
max[count-1]=score[i];? //此時(shí)count的值為1到3,賦值之后的數(shù)組max中的值從大到小排列
}
}
System.out.println("考試成績(jī)的前三名為:");
for(int x=0;x<3;x++) {
System.out.println(max);
}
}
2018-10-07
把max定義為數(shù)組
代碼如下
public void score() {
int max=0; //這個(gè)注釋掉
int[] max=new int[];?
int[] score= {89,-23,64,91,119,52,73};
for(int i=0;i<score.length;i++){
if(score[i]>=0 && score[i]<=100) {
if(max < score[i]) {
max=score[i];
}
改為:
max[i]=score[i];? ?//這時(shí)數(shù)組max里的值都為有效數(shù)值
}
}
Arrays.sort(max); //給數(shù)組max排序,從低到高
System.out.println("考試成績(jī)的前三名為:");
for(int x=0;x<3;x++) {
System.out.println(max);
}
改為:
for(int x=max.length-1;x>max.length-4||x>=0;x--){? ?//輸出數(shù)組后三個(gè)數(shù)值,若數(shù)組中的數(shù)值數(shù)量小于3,則輸出全部數(shù)值
????????System.out.println(max[x]);
}
}
2018-10-03
你在if條件下給max賦了值,max就會(huì)一直變到循環(huán)結(jié)束,之后成為一個(gè)定值,比如一百以內(nèi)最大值是89,max則在89時(shí)就不會(huì)變化。以至于在下面輸出時(shí)候只能輸出三個(gè)89。在這種前提下只是取出數(shù)組中一百以內(nèi)的最大值,不能得到一百以內(nèi)的前三大的值。
2018-10-02
按你這個(gè)自己定義的方法是無法輸出前三名的,只能輸出三次同一個(gè)最大值