问答详情
源自:7-1 编程练习

输出为什么不是[91,89,73],而是[0,0,73]?那两个0是怎么回事?

import java.util.Arrays;
public class HelloWorld {
    
    public static void main(String[] args) {
        int [] scores=new int[]{89,-23,64,91,119,52,73};
        HelloWorld a = new HelloWorld();
        a.b(scores,3);
    }
    
    public void b(int[]scores,int number){
        int j=0;
     Arrays.sort(scores);
        for(int i=scores.length-1;i>=0;i--){
            if(scores[i]<0||scores[i]>100){
                continue;
              }else{
              j++;
              int [] three=new int[number];
              System.out.println(j-1);
              System.out.println(scores[i]);
              three[j-1]=scores[i];
              if(j==3){
                 System.out.println(Arrays.toString(three));
                 break;
              }
            }
            
        }
    }                   
}

提问者:694710752 2016-12-22 23:11

个回答

  • 松shine
    2016-12-23 07:49:58

    把int [] three=new int[number];放在 for循环外面就正确了。因为每次循环都重新定义数组three,并把之前的值覆盖,所以前面两个元素都为0。