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

nhjlsmyf  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(539)

我想划界 ,\\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;
    }
ldfqzlk8

ldfqzlk81#

useDelimiter 接收正则表达式。所以,在你的例子中,正确的字符串应该是 "(,\\s|\n)" . 或条件放在圆括号中,用单管而不是双管分隔。
您还可以参考这个极好的答案:如何在java scanner中使用分隔符?

laawzig2

laawzig22#

有时string.class本身足以满足您的需要。为什么不使用regex来拆分行并对结果进行操作呢?例如

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
}

相关问题