Reading contents of a file into a 2D array

后端 未结 2 1020
野性不改
野性不改 2021-01-17 02:27

I am fairly new to programming so layman\'s talk is appreciated.

I have been tasked to read the contents of a file, which will contain 9 values (3x3 array) and then

相关标签:
2条回答
  • 2021-01-17 02:33

    ok, the way I look to it: you read the content of the input file to a string. You already have the method for reading line by line just put everything in a string.

    String content = readFile(input.txt);
    
    // Parse lines
    
    String[] lines = content.split("\n");
    
    // Parses values
    
    for(int i = 0; i < lines.length; i++)  {
        // Get line values
        String[] values = lines[i].split(" ");
        for(int j = 0; j < values.length; j++) {
            // Punt in Matrix
            matrix[i][j] = Double.parseDouble(values[j]);
        }
    }
    
    0 讨论(0)
  • 2021-01-17 02:47

    You're missing an extra step here.

    Once you read the line, you have to then split the line and parseDouble on individual numbers.

    int lineCount = 0;
    while ((line = bf.readLine()) != null)
    {
        String[] numbers = line.split(" ");
        for ( int i = 0 ; i < 3 ; i++) 
             matrix[lineCount][i] = Double.parseDouble(numbers[i]);
    
        lineCount++;
    }
    

    Also, your readFile doesn't need to return anything. Just make your matrix variable global.

    0 讨论(0)
提交回复
热议问题