好吧,所以代码很简单。通用类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();
}
}
答案 0 :(得分:4)
原因是,您已拨打input.nextLine()
两次:
do {
set1.add(input.nextLine());
}
while (!"EXIT".equals(input.nextLine()));
比做的更简单的方法是:
while (!(String in = input.nextLine()).equals("EXIT")) {
set1.add(in);
}
答案 1 :(得分:0)
你要求输入两次
do {
set1.add(input.nextLine()); // you enter a number
}
while (!"EXIT".equals(input.nextLine())); // what if you enter another number?
// it'll just loop again, skipping that number
您需要输入一次并使用它来停止或添加到您的设置。
答案 2 :(得分:0)
你的循环正是你告诉它的......
set1
"EXIT"
因此,每隔一个请求用于检查退出状态。相反,您应该将输入中的文本分配给变量并使用它来进行检查,例如......
do {
String text = input.nextLine();
if (!"EXIT".equals(text)) {
set1.add();
}
} while (!"EXIT".equals(text));
ps-是的,我知道,您可以使用break
;)