好的,所以代码非常简单。泛型类ourSet,它接受一些元素,将其放入LinkedList,并对这两个集合执行一些功能。
我的问题实际上与项目的一般概念完全无关,更多的是在我创建的“用户输入界面”中。我希望它接收一些字符串并将其添加到集合中,然后在接收字符串“EXIT”(全部大写)时退出循环,并对下一组执行相同的操作。正在发生的事情是 do while 循环仅发送所有奇数的第 1、第 3、第 5、..。
package set.pkgclass;
import java.util.Scanner;
import java.util.LinkedList;
public class SetClass {
public static void main(String[] args) {
ourSet<String> set1 = new ourSet<String>();
ourSet<String> set2 = new ourSet<String>();
Scanner input = new Scanner(System.in);
System.out.println("Please enter a string to put in set 1, "
+ "type EXIT (in all caps) to end.");
do {
set1.add(input.nextLine());
}
while (!"EXIT".equals(input.nextLine()));
System.out.println("Please enter a string to put in set 2, "
+ "type EXIT (in all caps) to end");
do {
set2.add(input.nextLine());
}
while (!"EXIT".equals(input.nextLine()));
ourSet.intersection(set1,set2);
ourSet.difference(set1, set2);
ourSet.union(set1, set2);
}
}
class ourSet<T>{
private LinkedList<T> mySet = new LinkedList<>();
public void add(T element){
mySet.add(element);
}
public void remove(T element){
mySet.remove(element);
}
public boolean membership(T element){
if(mySet.contains(element) == true) {
return true;
}
else {
return false;
}
}
public static <T> void union(ourSet<T> s1, ourSet<T> s2){
System.out.print("The union is: ");
for (int i=0; i < s1.mySet.size(); i++) {
T t = s1.mySet.get(i);
if (!s2.mySet.contains(t)){
s2.add(t);
}
}
for (int i=0; i < s2.mySet.size(); i++){
T t = s2.mySet.get(i);
System.out.print(t+", ");
}
System.out.println();
}
public static <T> void intersection(ourSet<T> s1, ourSet<T> s2){
System.out.print("The intersection is: ");
for (int i=0; i < s1.mySet.size(); i++) {
T t = s1.mySet.get(i);
if (s2.mySet.contains(t)) {
System.out.print(t+", ");
}
}
System.out.println();
}
public static <T> void difference(ourSet<T> s1, ourSet<T> s2){
System.out.print("The difference is: ");
for (int i=0; i < s1.mySet.size(); i++) {
T t = s1.mySet.get(i);
if (!s2.mySet.contains(t)) {
System.out.print(t+", ");
}
}
System.out.println();
}
}