2016-03-04 34 views
-1

我想知道如果两个数组的前n个元素相等,下列布尔值是否返回true。换句话说,如果n是5,那么两个数组的前5个元素是相等的,并且该方法应该返回true。Java:根据用户输入检查两个数组的相等性

@Override 

public boolean equal(char[] s, char[] t, int n) {  
    //goes through each value in the s array 
    for (int i =0; i < s[n]; i++){      
     //goes through each value in the t array 
     for (int j = 0 ; i < t[n]; j++){       
      if (s[n] == t[n]){      
       return true;      
      }     
     } 
    }     
    return true; 
} 
+1

对于您来说,阅读关于Java编程语言的更多内容将是一个不错的主意。似乎你对某些基本概念有深刻的误解。 – blazs

回答

0

您不需要嵌套for循环。这是一个更简洁的算法。

public boolean equal(char[] s, char[] t, int n) { 

    //TODO: you can add checks to make sure n is less than the length of both of the arrays 

    for(int i = 0; i < n; i++){ 

     //For the first n elements, if they aren't equal just return false; 
     if(s[i] != t[i]){ 

      return false; 
     } 
    } 
    return true; 
} 
0

代码中有很多错误。以下是检查数组的第一个n条目是否相等的一种方法。

boolean equal(char[] t, char[] s, int n) { 
    if (s.length <= n || t.length <= n) { 
     throw new IllegalArgumentException("..."); 
    } 

    for (int i = 0; i < n; ++i) { 
     if (s[i] != t[i]) return false; 
    } 
    return true; 
} 
+0

@KedarMhaswade哎呀,谢谢你的注意! – blazs

相关问题