我是编程新手,以前从未使用过扫描仪。我遇到扫描仪无法识别某些字符的问题,或者至少这是我认为的问题所在。我必须编写的程序应该计算两组非负整数的交集,并集和集差。用户应输入两组,以逗号分隔,并用方括号括起来。例如:[1、2、3] + [4、3、10、0]。还要求我使用TreeSet,并使用适当的TreeSet方法对这两个集合执行请求的操作。目前,我收到的输出是:
输入非负整数列表,用逗号分隔并括在方括号中。
例如:[1、2、3] + [4、3、10、0]。
输入序列:[0,1,2,3] + [4,5,6] 输入错误:在设置开始处应为'['。
任何帮助将不胜感激。
import java.util.Scanner;
import java.util.TreeSet;
public class setCalculator {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter a list of non-negative integers, separated by commas, and enclosed in square brackets. ");
System.out.println("For example: [1, 2, 3] + [4, 3, 10, 0]. ");
while(true) {
System.out.print("\nEnter Sequences: ");
if(input.hasNext("\n")) {
break;
} try {
compute();
} catch (IllegalArgumentException e) {
System.out.println("Error in input: " + e.getMessage());
}
input.next();
}
}
public static void compute(){
TreeSet<Integer> setA, setB; // The two sets of integers.
setA = readSet();
if (! input.hasNext("\\+") && ! input.hasNext("\\-") && ! input.hasNext("\\*"))
throw new IllegalArgumentException("Expected *, +, or - after first set.");
setB = readSet();
if( input.hasNext("\n"))
throw new IllegalArgumentException("Extra unexpected input.");
if(input.hasNext("\\+"))
setA.addAll(setB); // Union.
else if (input.hasNext("\\*"))
setA.retainAll(setB); // Intersection.
else
setA.removeAll(setB); // Set difference.
System.out.print("Value: " + setA);
/*
* Start with an empty set.
Read the '[' that begins the set.
Repeat:
Read the next number and add it to the set.
If the next character is ']':
break.
Read the comma that separates one number from the next.
Read the ']'.
Return the set.
*/
}
private static TreeSet<Integer> readSet() {
TreeSet<Integer> set = new TreeSet<Integer>();
if(! input.hasNext("\\[")) {
throw new IllegalArgumentException("Expected '[' at start of set.");
}
if(input.hasNext("\\[")){
input.nextLine();
return set;
}
while (true) {
// Read the next integer and add it to the set.
if (! input.hasNextInt())
throw new IllegalArgumentException("Expected an integer.");
int n = input.nextInt(); // Read the integer.
set.add(Integer.valueOf(n)); // (Could have just said set.add(n)!)
if (input.hasNext("\\)"))
break; // ']' marks the end of the set.
else if (input.hasNext("\\,"))
input.next(); // Read a comma and continue.
else
throw new IllegalArgumentException("Expected ',' or ']'.");
}
input.next(); // Read the ']' that ended the set.
return set;
}
}
答案 0 :(得分:1)
问题可能出在您使用Scanner.hasNext()
上。特别是在if(input.hasNext("\\[")){
上。如果我没记错的话,这将检查完整的令牌,这显然不仅仅是“ [”。
总体而言,您的方法使问题变得更加复杂。我个人不会使用扫描仪完成整个任务。只需从扫描器中获取输入,然后对检索到的String进行输入验证就容易得多。
此简短代码段将从扫描仪获取输入,将其保存在字符串中,并从提供的字符串中解析Set
。 (但是肯定有更有效的解决方案)
编辑:
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the sequence:");
// read the whole input
String input = scanner.nextLine();
// find the operator
String op = findOperator(input);
// split the String on "+"
String[] sets = input.split("\\" + op);
if (sets.length != 2) {
// raise exception for incorrect input
return;
}
TreeSet<Integer> setA = parseSet(sets[0]);
TreeSet<Integer> setB = parseSet(sets[1]);
TreeSet<Integer> resultSet = computeResultSet(setA, setB, op);
System.out.println(resultSet);
}
private static String findOperator(String input) {
char[] operators = { '+', '-', '*' };
for (char c : operators) {
if (input.indexOf(c) != -1) {
return "" + c;
}
}
// operator not found -> wrong input -> exception handling
return "";
}
private static TreeSet<Integer> parseSet(String input) {
TreeSet<Integer> outputSet = new TreeSet<Integer>();
// remove whitespaces
input = input.trim();
// check if the input has the correct format
if (!input.startsWith("[") || !input.endsWith("]")) {
// exception for incorrect input
return outputSet;
}
// remove the braces
input = input.substring(1, input.length() - 1);
// add the integers to the set
String[] digits = input.split(",");
for (String singleDigit : digits) {
outputSet.add(Integer.parseInt(singleDigit.trim()));
}
return outputSet;
}
private static TreeSet<Integer> computeResultSet(TreeSet<Integer> setA, TreeSet<Integer> setB, String op) {
TreeSet<Integer> resultSet = new TreeSet<Integer>();
if (op.equals("+")) {
setA.addAll(setB);
} else if (op.equals("-")) {
setA.removeAll(setB);
} else if (op.equals("*")) {
setA.retainAll(setB);
}
resultSet = setA;
return resultSet;
}
输入:
Enter the sequence:
[1,2,3] - [2,3]
输出:
[1]