我遇到扫描仪无法识别某些字符的问题

I am having issues with the scanner not recognizing certain characters

我是编程新手,以前从未使用过扫描仪。我遇到了扫描仪无法识别某些字符的问题,或者至少我认为这是问题所在。我必须编写的程序应该计算两组非负整数的交集、并集和集差。用户应输入以逗号分隔并括在方括号中的两组。例如:[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;
}
}

问题可能出在您对 Scanner.hasNext() 的使用上。特别是 if(input.hasNext("\[")){。如果我没记错的话,这将检查完整的令牌,这显然不仅仅是 "[".

总体而言,您的方法使问题过于复杂。我个人不会用扫描仪完成整个任务。简单地从扫描仪获取输入,然后对检索到的字符串进行输入验证会更容易。

这个简短的代码片段将从扫描仪获取输入,将其保存在一个字符串中,并从提供的字符串中解析 Sets。 (但肯定有更有效的解决方案)

编辑:

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]