这是我类的一种方法,用于检查两个序列是否按某种顺序具有相同的值,忽略重复项。
例如:
第一 : 3 3 2 1 1
第二 : 2 3 1
在此方法中,它们被认为是相同的。
然而
第一 : 3 3 2 1 1
第二 : 3 3 1 1
被认为不一样。
'
public boolean sameValues(Sequence other)
{
int counter1 = 0;
int counter2 = 0;
//consider whether they are the same from first to second
for(int i = 0; i > values.length; i++)
{
for(int n = 0; n > other.len(); n++)
{
counter1++;
if(values[i] == other.get(n))
{
break;
}
}
if(values[i] != other.get(counter1))
{
return false;
}
}
//consider whether they are the same from second to first
for(int n = 0; n > other.len(); n++)
{
for(int i = 0; i > values.length; i++)
{
counter2++;
if(values[i] == other.get(n))
{
break;
}
}
if(values[counter2] != other.get(n))
{
return false;
}
}
return true;
}
'
但是,无论我导入什么,答案永远是正确的。
'
import java.util.Scanner;
import java.util.Arrays;
public class SameValuesTester
{
public static void main(String[] args)
{
Sequence first = new Sequence(20);
Sequence second = new Sequence(20);
int firstCounter = 0;
int secondCounter = 0;
//import the first array
Scanner x = new Scanner(System.in);
System.out.println("Please enter the values" +
"for the first sequence with q to quit.");
for(int i = 0; x.hasNextInt(); i++)
{
first.set(i, x.nextInt());
firstCounter++;
}
//import the second array
Scanner y = new Scanner(System.in);
System.out.println("Please enter the values" +
"for the second sequence with q to quit.");
for(int j = 0; y.hasNextInt(); j++)
{
second.set(j, y.nextInt());
secondCounter++;
}
//.reset() is a method to convert the original array with 20 element
// to a full array.
first.reset(firstCounter);
second.reset(secondCounter);
//compare two Sequence
System.out.println(first.sameValues(second));
}
}
'
你可以做的是从你的Arrays
创建两个HashSet
,并使用HashSet.containsAll()
来测试它们是否包含相同的元素:
//Arrays as input
Integer[] array1 = {3, 3, 2, 1, 1};
Integer[] array2 = {2, 3, 1};
Set<Integer> set1 = new HashSet<Integer>();
Set<Integer> set2 = new HashSet<Integer>();
//Fill set1 and set2 from array1 & array2
Collections.addAll(set1, array1);
Collections.addAll(set2, array2);
//return result
return set1.containsAll(set2) && set2.containsAll(set1);
有两个问题。
首先,有一个错别字(>
而不是警卫中的<
)。从不满足保护条件,该条件始终返回 true。
另一个归结为计数器的处理方式。您需要一个 while 循环,在找到值时中断,然后检查计数器是否位于数组的末尾,在这种情况下,这是一个 false。
public boolean sameValues(Sequence other)
{
//consider whether they are the same from first to second
for(int i = 0; i < values.length; i++)
{
int counter = 0;
while(counter < other.len())
{
if(values[i] == other.get(counter))
{
break;
}
counter++;
}
if(counter == other.len())
{
return false;
}
}
//consider whether they are the same from second to first
for(int n = 0; n < other.len(); n++)
{
int counter = 0;
while(counter < values.length)
{
if(other.get(n) == values[counter])
{
break;
}
counter++;
}
if(counter == values.length)
{
return false;
}
}
return true;
}