当1
在变量中的位置等于另一个变量中的1
的位置时,我正试图计算在两个变量之间的数组中出现True
的次数,依此类推。
我试过:
public class another_test {
public static void main(String[] args) {
String[] x = new String[]{"win", "win", "lose"};
String[] y = new String[]{"win", "lose", "lose"};
int z=0;
if(x.equals(y)) {
z++;
}
System.out.println(z); //output = 0
}
我应该得到的答案是2
,如何解决这个问题?
您可以执行以下操作:
public static void main(String[] args) {
String[] x = new String[]{"win", "win", "lose"};
String[] y = new String[]{"win", "lose", "lose"};
int z=0;
for (int i = 0; i < x.length && i < y.length; i++) {
if(x[i].equals(y[i])) {
z++;
}
}
System.out.println(z);
}
另一种方法(功能(:
long z = IntStream.range(0, Math.min(x.length, y.length))
.filter(i -> x[i].equals(y[i]))
.count();
System.out.println(z);
输出:
2
@Lime有两个String数组。您需要比较同一索引的两个数组中的元素(无论它们是否相似(。
您可以简单地使用for循环,其中i
将用作索引,并且它应该小于两个数组的长度。
public static void main(String[] args) {
String[] x = new String[]{"win", "win", "lose"};
String[] y = new String[]{"win", "lose", "lose"};
int noOfTrueOccur=0;
for (int i = 0; i < x.length && i < y.length; i++) {
//here you are comparing actual String content
if(x[i].equals(y[i])) {
noOfTrueOccur++;
}
}
System.out.println(noOfTrueOccur); //Output=2
}
这是一种简单的方法。还有其他方法。