java - 需要写一定的方法

标签 java arrays methods equals

所以我有一个家庭作业问题。这就是我需要做的:

Write the definition of a method , oddsMatchEvens , whose two parameters  are arrays  of integers  of equal  size. The size of each array  is an even number. The method  returns true  if and only if the even-indexed elements  of the first array  equal  the odd-indexed elements  of the second, in sequence. That is if w is the first array  and q the second array , w[0] equals  q[1], and w[2] equals  q[3], and so on.

我拥有的是:

public boolean oddsMatchEvens(int[] w, int[] q){
int count = 0;

for(int i=0; i < w.length; i++){
if(w[i].equals(q[i + 1])){
count++;
if(count == w.length){
return true;
}
}
}

我收到此错误:

  

⇒     You almost certainly should be using: &&
     ⇒     You almost certainly should be using: +=
     ⇒     You almost certainly should be using: >=

最佳答案

试试这个:

if(w[i] == q[i + 1])

“等于”方法用于对象。

当然,必须始终返回 boolean 值。

该方法的工作版本:

public boolean oddsMatchEvens(int[] w, int[] q) {
    int count = 0;
    for (int i = 0; i < w.length; i++) {
        if (w[i] == q[i + 1]) {
            count++;
            if (count == w.length) {
                return true;
            }
        }
    }

    return false;
}

关于java - 需要写一定的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18483471/

相关文章:

java - 完成交换整数数组的前半部分和后半部分的方法

JavaScript 函数对象方法 - getter 和 setter

java - 在 Spring MVC Hibernate 应用程序中使用属性文件时抛出错误?

java - Java Play! 是否有审计工具?框架

java - 如何解决 SSLPeerUnverifiedException : peer not authenticated after using InstallCert. java

java - Spring Boot 服务静态资源 - sitemap.xml

arrays - 使用数组 VBA 初始化对象

arrays - Swift - 数组[任何索引]?

java - 如何知道Java方法的字节码大小

java - 难度设置变量