扫描仪使用的分隔符获取图案

时间:2018-10-16 21:45:10

标签: java java.util.scanner

如何在usedelimiter中获得图案?例如:

sc = new Scanner(new File("polinom.txt"));
sc.useDelimiter("[+-]");

我想在sc.next()之前获得标志。谢谢您的帮助。

1 个答案:

答案 0 :(得分:0)

也许根本不使用 Scanner#next()方法。在 while 循环条件下使用 Scanner#hasNextLine()读取整个文件行,并使用 Scanner#nextLine()读入整个文件行变量,然后解析该行以获取所使用的运算符。您可以将 String#split()方法与正则表达式"[\\+\\-\\\\*\\/]"一起使用,以在 plus minus < / em>,运算符。

现在遍历拆分值数组并构建一个临时字符串。对原始行使用此临时字符串的长度以及String#substring()方法,以获取拆分所基于的运算符。听起来真令人困惑,对吗? 种类 类似于对原始拆分过程进行反向工程。这是一个代码示例:

如果我们有一个名为 polinom.txt 的文本文件,其中包含:

2+2-1
3 * 3 + 2 - 1
6+6
44 / 6 + 7-7
6+1+2+4

,我们运行以下代码:

try (Scanner sc = new Scanner(new File("polinom.txt"))) {
    StringBuilder tmp;
    while (sc.hasNextLine()) {
        String line = sc.nextLine().replace("\\","/");
        System.out.println("EQUATION:\t" + line);

        // Split the Equation line on the +, -, *, and / operators
        String[] equationNumbers = line.split("[\\+\\-\\\\*\\/]");
        String[] operators = new String[equationNumbers.length - 1];
        tmp = new StringBuilder();
        for (int i = 0; i < equationNumbers.length; i++) {
            System.out.println("\tEquation Number " + (i + 1) + " is: " + equationNumbers[i].trim());
            tmp.append(equationNumbers[i]);
            if (i < operators.length) {
                operators[i] = line.substring(tmp.length(), tmp.length() + 1);
                System.out.println("\t\tOperator after Number is: " + operators[i]);
                tmp.append(operators[i]);
            }
        }
        System.out.println();
    }
}
catch (FileNotFoundException ex) {
    Logger.getLogger("Get Operators").log(Level.SEVERE, null, ex);
}

您应该在控制台窗口中看到的是:

EQUATION:   2+2-1
    Equation Number 1 is: 2
        Operator after Number is: +
    Equation Number 2 is: 2
        Operator after Number is: -
    Equation Number 3 is: 1

EQUATION:   3 * 3 + 2 - 1
    Equation Number 1 is: 3
        Operator after Number is: *
    Equation Number 2 is: 3
        Operator after Number is: +
    Equation Number 3 is: 2
        Operator after Number is: -
    Equation Number 4 is: 1

EQUATION:   6+6
    Equation Number 1 is: 6
        Operator after Number is: +
    Equation Number 2 is: 6

EQUATION:   44 / 6 + 7-7
    Equation Number 1 is: 44
        Operator after Number is: /
    Equation Number 2 is: 6
        Operator after Number is: +
    Equation Number 3 is: 7
        Operator after Number is: -
    Equation Number 4 is: 7

EQUATION:   6+1+2+4
    Equation Number 1 is: 6
        Operator after Number is: +
    Equation Number 2 is: 1
        Operator after Number is: +
    Equation Number 3 is: 2
        Operator after Number is: +
    Equation Number 4 is: 4