有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

阵列单行Java扫描器以从文件中读取矩阵

我一直在用这个;一种单衬里:

public static String[] ReadFileToStringArray(String ReadThisFile) throws FileNotFoundException{
    return (new Scanner( new File(ReadThisFile) ).useDelimiter("\\A").next()).split("[\\r\\n]+");
}

要读取具有此类内容(即,具有字符串标记)的文件,请执行以下操作:

abcd
abbd
dbcd

但是,现在我的文件内容是这样的:

1 2 3 4
1 2 2 4
1 5 3 7
1 7 3 8

我希望这些值被读取为整数

我见过这些{a1}、{a2}和{a3}问题,但它们没有回答我的问题

我尝试了以下操作,但失败了:

public static int[][] ReadFileToMatrix(String ReadThisFile) throws FileNotFoundException{
    return (new Scanner( new File(ReadThisFile) ).useDelimiter("\\A").nextInt()).split("[\\r\\n]+");
}

错误消息:无法调用基元类型int上的split(String)我理解这条信息,知道它错得可怕:)

有人能提出实现这一目标的正确方法吗

请注意,对于带有回路的解决方案,“否”


共 (3) 个答案

  1. # 1 楼答案

    使用Java 8,您可以使用Lambdas:

    public static int[][] readFileToMatrix(String readThisFile) throws FileNotFoundException{
        return Arrays.stream((new Scanner( new File(readThisFile) ).useDelimiter("\\A").nextInt()).split("[\\r\\n]+")).mapToInt(Integer::parseInt).toArray();
    }
    

    否则,没有循环就无法完成。您有一个String[]数组,并且希望逐个为每个元素调用Integer.parseInt()

  2. # 2 楼答案

    当基本的BufferedReaderInteger.parseInt(line.split(" ")[n]);一起使用时,使用类似乎过于复杂了

  3. # 3 楼答案

    如果您使用Java7或更高版本,您可以使用类似的东西。我想不出一种方法可以在一行中不循环地完成它。把它放到methode中,然后调用它

    //Read full file content in lines
    List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
    
    int NR_OF_COLUMNS = 4;
    int NR_OF_ROWS = lines.size();
    
    int[][] result = new int[NR_OF_ROWS][NR_OF_COLUMNS];
    
    for(int rowIndex = 0; rowIndex < NR_OF_ROWS; rowIndex++)
    {
        String[] tokens = lines.get(rowIndex).split("\\s+");  //split every line
        for(int columnIndex = 0; columnIndex < NR_OF_COLUMNS; columnIndex++)
            result[rowIndex][columnIndex] = Integer.parseInt(tokens[columnIndex]);   //convert every token to an integer
    }
    return result;