我正在尝试使用 Arrays.sort() 方法对整数数组进行排序。调用该方法后,数组元素变为0。
下面是我的代码
import java.util.Arrays;
import java.util.Scanner;
public class WillMuggerWin {
public static void main(String ar[]){
int t,n=10,m=5,sum=0,flag=0;
int notes[]=new int[20];
Scanner s=new Scanner(System.in);
t=s.nextInt();
for(int i=0;i<t;i++){
n=s.nextInt();
m=s.nextInt();
int temp=m;
// System.out.println("m:"+m+"n:"+n);
for(int j=0;j<n;j++){
notes[j]=s.nextInt();
}
System.out.println("note:"+notes[0]+" "+notes[1]+" "+notes[2]);
Arrays.sort(notes);
System.out.println("note:"+notes[0]+" "+notes[1]+" "+notes[2]);
//System.out.println("note1"+notes[0]);
for(int k=n-1;k>=0;k--){
//System.out.println("notes "+notes[k]);
if(notes[k]<=temp){
sum=sum+notes[k];
System.out.println("sum: "+sum);
temp=temp-sum;
if(temp==0){
flag=1;
break;
}
}
}
if(flag==1)
System.out.println("Yes");
else
System.out.println("No");
flag=0;
sum=0;
}
}
}
输入:
5 3 3 1 1 1
输出:
note:1 1 1
note:0 0 0
sum: 0
sum: 0
sum: 0
No
我的代码有什么问题吗?
最佳答案
你的数组不仅有 3 个元素,它还因为这一行而变得更长:
int notes[] = new int[20];
如果您想查看问题的原因,请添加以下行:
System.out.println(Arrays.toString(notes));
在你的第一个之前:
System.out.println("note:"+notes[0]+" "+notes[1]+" "+notes[2]);
行,您将看到整个数组:
[1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
这就是为什么您会看到 0
排序后的前 3 位,因为该数组还包含很多 0
在那些1
之后s。
所以,sort
方法具有预期的行为。
关于java - 应用 Array.sort() 函数后数组元素变为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41652927/