Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/google-chrome/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 我遇到扫描仪无法识别某些字符的问题_Java_Java.util.scanner - Fatal编程技术网

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

Java 我遇到扫描仪无法识别某些字符的问题,java,java.util.scanner,Java,Java.util.scanner,我是编程新手,以前从未使用过扫描仪。我的扫描仪无法识别某些字符,或者至少我认为这就是问题所在。我要做的程序应该计算两组非负整数的交集、并集和集差。用户应输入两组数据,用逗号分隔,并用方括号括起来。例如:[1,2,3]+[4,3,10,0]。我还被要求使用TreeSet,并使用适当的TreeSet方法对这两个集合执行请求的操作。目前,我收到的输出是: 输入非负整数列表,用逗号分隔,并用方括号括起来。 例如:[1,2,3]+[4,3,10,0] 输入顺序:[0,1,2,3]+[4,5,6] 输入错误

我是编程新手,以前从未使用过扫描仪。我的扫描仪无法识别某些字符,或者至少我认为这就是问题所在。我要做的程序应该计算两组非负整数的交集、并集和集差。用户应输入两组数据,用逗号分隔,并用方括号括起来。例如:[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;
}
}
import java.util.Scanner;
导入java.util.TreeSet;
公共类集合计算器{
静态扫描仪输入=新扫描仪(System.in);
公共静态void main(字符串[]args){
System.out.println(“输入非负整数列表,用逗号分隔,并用方括号括起来”);
System.out.println(“例如:[1,2,3]+[4,3,10,0]”;
while(true){
系统输出打印(“\n输入序列:”);
if(input.hasNext(“\n”)){
打破
}试一试{
compute();
}捕获(IllegalArgumentException e){
System.out.println(“输入错误:+e.getMessage());
}
input.next();
}
}
公共静态void compute(){
TreeSet setA,setB;//两组整数。
setA=readSet();
如果(!input.hasNext(\\+)&&!input.hasNext(\\-)&&!input.hasNext(\\*))
在第一组之后抛出新的IllegalArgumentException(“预期*、+、或-”);
setB=readSet();
if(input.hasNext(“\n”))
抛出新的IllegalArgumentException(“额外意外输入”);
if(input.hasNext(\\+))
setA.addAll(setB);//并集。
else if(input.hasNext(\\*)
setA.retainal(setB);//交叉点。
其他的
setA.removeAll(setB);//设置差异。
系统输出打印(“值:+setA”);
/*
*从一个空的集合开始。
读取集合开头的“[”号。
重复:
阅读下一个数字并将其添加到集合中。
如果下一个字符为']':
打破
阅读分隔一个数字和下一个数字的逗号。
阅读“]”。
把电视机还给我。
*/
}
私有静态树集readSet(){
树集=新树集();
如果(!input.hasNext(“\\[”){
抛出新的IllegalArgumentException(“在集合开始时应为“[”);
}
if(input.hasNext(“\\[”){
input.nextLine();
返回集;
}
while(true){
//读取下一个整数并将其添加到集合中。
如果(!input.hasNextInt())
抛出新的IllegalArgumentException(“应为整数”);
int n=input.nextInt();//读取整数。
set.add(Integer.valueOf(n));/(可以说set.add(n)!)
if(input.hasNext(\\))
break;/']'标记集合的结束。
else if(input.hasNext(\\,“”)
input.next();//读取逗号并继续。
其他的
抛出新的IllegalArgumentException(“预期”、“或”].”);
}
input.next();//读取结束集合的']'。
返回集;
}
}

问题可能在于您使用了
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;
}
输出:

[1]

你好!欢迎来到StAdvExcel!你试过调试这个例子看看发生了什么吗?调试器是你的朋友,早点学习,这将是你的编程冒险中的一个很棒的盟友。同时,请考虑如何减少这个问题,以显示一个最小的例子,帮助别人更好地理解这个问题。dvice here:Hi@wobr,感谢您的回复和建议链接。我尝试过使用调试器,从使用调试器来看,问题似乎在readSet()中方法,但我不是100%确定这就是我添加整个程序的原因。嗨@maloomeister,谢谢你的回答。你提供的代码片段可以工作。我一直在尝试使用你在我的帖子中与计算方法共享的内容来获得下面的输出,但我仍然无法使其工作。输入输出-------------------[1,2,3]+[3,5,7][1,2,3,5,7][10,9,8,7]*[2,4,6,8][8][5,10,15,20][0,10,20][5,15]啊,现在我明白你想做什么了。你正在使用操作符作为指示集应该是什么样子的。这不是我现在回答的一部分。让我更新它。
[1]