扫描仪输入接受字符串跳过while循环内的所有其他输入。

好吧,所以代码很简单。 通用类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 set1 = new ourSet(); ourSet set2 = new ourSet(); 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{ private LinkedList 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  void union(ourSet s1, ourSet 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  void intersection(ourSet s1, ourSet 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  void difference(ourSet s1, ourSet 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(); } } 

原因是,您正在调用input.nextLine() 两次

 do { set1.add(input.nextLine()); } while (!"EXIT".equals(input.nextLine())); 

比起来更简单的方法是:

 while (!(String in = input.nextLine()).equals("EXIT")) { set1.add(in); } 

你要求输入两次

 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 

您需要输入一次并使用它来停止或将其添加到您的集合中。

你循环正在完成你告诉它的…

  • 读取一行文本并将其添加到set1
  • 阅读一行文字并检查它是否等于"EXIT"
  • 根据需要重复……

因此,每隔一个请求用于检查退出状态。 相反,您应该将输入中的文本分配给变量并使用它来进行检查,例如……

 do { String text = input.nextLine(); if (!"EXIT".equals(text)) { set1.add(); } } while (!"EXIT".equals(text)); 

ps-是的,我知道,你可以使用break ;)