java如何比较第一个数组的每个元素和第二个数组的每个元素
如何比较第一个数组的第n个元素与第二个数组的第n个元素
- 假设第一个数组的第一个元素大于第二个数组的第一个元素
- 比较两个数组的第二个元素
- 如果两个元素都大于第二个数组print
WIN
- 如果第一个数组的一个元素小于第二个数组,则打印
LOSE
如果第一个数组的所有元素大于第二个数组的所有元素,则printWIN
否则printLOSE
例1:
6
10 20 50 100 500 400
30 20 60 70 90 490
LOSE
例2:
5
10 20 30 40 50
40 50 60 70 80
WIN
说明:
在第一个输入中,数组大小为6 由于array2索引3小于array1索引3,因此它会丢失打印 但在第二次输入中,array2中的所有元素都大于array1中的元素,因此它会打印win
import java.util.*;
public class CandidateCode {
public static void main(String args[] ) throws Exception {
Scanner sc=new Scanner(System.in);
int i,j;
int n=sc.nextInt();
int a[]=new int[n];
int b[]=new int[n];
for(i=0;i<n;i++)
a[i]=sc.nextInt();
for(j=0;j<n;j++)
b[j]=sc.nextInt();
for(i=0;i<a.length;i++){
for(j=0;j<b.length;j++){
if(b[j]>a[i]){
System.out.println("WIN");
}else
System.out.println("LOSE");
}
}
}
}
# 1 楼答案
您需要采取不同的方法,您的情况是:
你现在要做的是:要求所有更大的数字,用另一种方式问,当你发现一个数字低于第一个数组中的数字时,你就输了。因此:
创建一个标志变量,我们称之为
win
改变你的状况
发件人:
致:
在该条件内,将标志更改为
false
,这意味着第二个数组中至少有一个值低于第一个数组中的值。打破循环然后只需在
win
中输入值:你完了
您的代码应该是这样的(我改进了间距以提高可读性,您也应该这样做,我还为循环添加了大括号以提高可读性)
示例输出:
# 2 楼答案
首先,实际上只需要一个循环。由于两个阵列的大小相同,因此无需第二个循环即可对其进行比较:
由于您的代码可能会为每个具有更高值的索引打印“WIN”,因此可能有一个不错的解决方法。您可以做的是在代码的开头设置一个变量,并且只有在满足特定需求时才对其进行更改。然后,您可以插入一个打印,作为带有所述变量的最后一行: