0

这是一个示例输入文本文件:

some text
one more line of text
another line
and one more
1 23 3
2 34 4
5 12 4
3 23 8

我需要提取每一列数值并对其执行一些数学运算。

这是我到目前为止所尝试的:

Path inputFile = Paths.get(args[0]);

            try{
                ArrayList<String> lines = (ArrayList<String>) Files.readAllLines(inputFile, Charset.defaultCharset());
                ArrayList<String []> columns = new ArrayList<>();
                for(String line : lines){
                    columns.add(line.split("\\s"));
                }
                // Now for each line you have columns.
                for(String [] s : columns){ 
                    System.out.println(Arrays.toString(s));
                }

但它只是不正确,我无法摆脱这种僵局。任何帮助将不胜感激..

4

1 回答 1

1

我会说 ...

for(String line : lines){
                // Just add this condition
                if(line.matches("^[0-9]"){
                    // then process the way you want to...
                }   
            }

希望这可以帮助...

编辑:

Path inputFile = Paths.get(args[0]);

    try{
        ArrayList<String> lines = (ArrayList<String>) Files.readAllLines(inputFile, Charset.defaultCharset());
        ArrayList<String []> columns = new ArrayList<>();
        for(String line : lines){
            if(line.matches("^[0-9]")){
                System.out.println("Line:"+line);
                String[] colms = line.split("\\s+");
                    columns.add(colms);
                for (int i = 0; i < colms.length; i++) {
                    String temp = colms[i];
                    System.out.println("Colmns:"+i+":"+temp);
                    // process temp one by one
                }
            }
        }
    }catch(Exception ex){
        ex.printStackTrace();
        System.out.println("Exception...");
    }
于 2013-09-16T00:49:51.233 回答