我们有两个diff数组,即 array1 & array2 。单独查找和比较。他们的总和和打印'-1'如果第一个数组的总和小于第二个数组ells print '1'。
int array1[] = new int[3]; // array one
int array2[] = new int[3]; // array two
int sum1= 0, sum2= 0;
for(int i=0; i<=2; i++){
array1[i] = scanner.nextInt(); // storing value by user in first array
array2[i] = scanner.nextInt(); // storing value by user in second array
}
for(int a1 : array1){
sum1 += a1; // sum of array
}
for(int a2 : array2){
sum2 += a2; // sum of array2
}
if(sum1<sum2){
System.out.print("-1");} //print -1 if sum1 is less than sum2
else{
System.out.println("1");}
我正在尝试尽可能紧凑,但我不知道该怎么做。 谁能告诉我此代码的紧凑程序
您可以用一个循环替换3个循环:
for(int i=0; i<=2; i++){
array1[i] = scanner.nextInt(); // storing value by user in first array
array2[i] = scanner.nextInt(); // storing value by user in second array
sum1 += array1[i];
sum2 += array2[i];
}
尝试以下:
int sum1 = Arrays.stream(array1).sum();
int sum2 = Arrays.stream(array2).sum();
int result = Integer.compare(sum1, sum2); //-1, 0 or 1
System.out.println("" + result);
或短:
System.out.println("" + Integer.compare(Arrays.stream(array1).sum(), Arrays.stream(array2).sum()));