如何使用2个以上的分隔符

时间:2017-10-31 21:25:31

标签: java delimiter

我想界定,\\s,但我也想界定\n,我到目前为止的想法是,\\s||\n,但是这没有用,有人有个主意吗?它当然是作为分隔符,但它回复IPHONE , 7.0, 4, ., 7, A, false, 0,而我想要回IPHONE 7, 4.7, A10, GSM, JET BLACK, 32GB, TRUE, 700

我正在扫描的文件是:

IPHONE 7, 4.7, A10, GSM, JET BLACK, 32GB, TRUE, 700
IPAD AIR 2, 9.7, A8, TRUE, SILVER, 64GB, 400

我用来扫描它的代码是:

public static iPhone read(Scanner sc) {
        boolean touchtech = false;
        //int price = 12;
        sc.next();
        sc.useDelimiter(",\\s||\n");
        String model = sc.next();
        double screensize = sc.nextDouble();
        String processor = sc.next();
        String modem = sc.next();
        String color = sc.next();
        String memory = sc.next();
        String touchtechtest = sc.next();
        if(touchtechtest.equals("TRUE")) {
            touchtech = true;
        }
        int price = sc.nextInt();
        sc.close();
        iPhone res = new iPhone(model, screensize, processor, modem, color, memory, touchtech, price);
        return res;
    }

2 个答案:

答案 0 :(得分:0)

useDelimiter收到正则表达式。因此,在您的情况下,正确的字符串将是"(,\\s|\n)"。您的OR条件进入圆括号,并由单个管道分隔,而不是双管道。

你也可以参考这个优秀的答案: How do I use a delimiter in Java Scanner?

答案 1 :(得分:0)

有时String.class本身足以满足您的需求。为什么不使用正则表达式分割线并对结果进行操作?例如

public static iPhone read(Scanner sc) { // Better yet just make it received a String
    final String line = sc.nextLine();
    final String [] result = line.split("(,)\\s*");

    // count if the number of inputs are correct
    if (result.length == 8) {
        boolean touchtech = false;
        final String model = result[0];
        final double screensize = Double.parseDouble(result[1]);
        final String processor = result[2];
        final String modem = result[3];
        final String color = result[4];
        final String memory = result[5];
        final String touchtechtest = result[6];
        if(touchtechtest.equals("TRUE")) {
            touchtech = true;
        }
        final int price = Integer.parseInt(result[7]);
        return new iPhone(model, screensize, processor, modem, color, memory, touchtech, price);
    }
    return new iPhone();// empty iphone
}