簡體   English   中英

我遇到掃描儀無法識別某些字符的問題

[英]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("\\\\[")){ 如果我沒記錯的話,這將檢查完整的標記,這顯然不僅僅是“[”。

總的來說,你的方法使問題過於復雜。 我個人不會使用掃描儀完成整個任務。 簡單地從掃描儀獲取輸入然后對檢索到的字符串進行輸入驗證會更容易。

這個簡短的片段將從掃描儀中獲取輸入,將其保存在一個字符串中,並從提供的字符串中解析Set s。 (但肯定有更有效的解決方案可能)

編輯:

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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM