这是我课程中的一个方法,用于检查两个序列是否具有相同的值(忽略重复项)。
例如:
第一个序列 :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));
}
}
'
3 3 2 1 1
和2 3 1
是相同的,但是3 3 2 1 1
和3 3 1 1
不是相同的? - Anthony C