Java:根据用户输入检查两个数组是否相等
Java: Check equality of two arrays based on user input
我想看看如果两个数组的前 n 个元素相等,下面的布尔值 return 是否为真。换句话说,如果 n 为 5,则两个数组的前 5 个元素相等,该方法应该 return true.
@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;
}
你的代码有很多错误。下面是检查数组的前 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;
}
您不需要嵌套的 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;
}
我想看看如果两个数组的前 n 个元素相等,下面的布尔值 return 是否为真。换句话说,如果 n 为 5,则两个数组的前 5 个元素相等,该方法应该 return true.
@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;
}
你的代码有很多错误。下面是检查数组的前 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;
}
您不需要嵌套的 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;
}