简体   繁体   中英

Reading in a 2D array from a file through the command line in Java

I need to read in a matrix from a file. I can read in the file fine, but if each line starts with a space then I get an error. How do I get around this? I don't know if I'm doing this correct. Heres part of my code:

import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.File;

public class factor {
public static void PrintMatrix(double[][] matrix) {
    int size = matrix[0].length;

    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            System.out.printf("%4.4f ", matrix[i][j]);
        }

        System.out.println();
    }

    System.out.println();
}

public static void main(String[] args) {
    if (args.length < 1) {
        System.out.println("You must supply a file to load the matrix from.");

        return;
    }

    Scanner s;
    double[][] a;
    double[][] l;
    double[][] u; 
    String line;
    int n;
    String[] nums;

    try {
        s = new Scanner(new File(args[0]));
    } catch (FileNotFoundException ex) {
        System.out.println("File not found.");

        return;
    }

    if (s.hasNext()) {
        line = s.nextLine();

        nums = line.split("\\s+");
        n = nums.length;
        a = new double[n][n];
        l = new double[n][n];
        u = new double[n][n];

        for (int i = 0; i < n; i++) {
            a[0][i] = Double.parseDouble(nums[i]);
        }
    } else {
        System.out.println("Nothing found in file.");

        return;
    }

    for (int i = 1; i < n; i++) {
        nums = s.nextLine().split("\\s+");

        for (int j = 0; j < n; j++) {
            a[i][j] = Double.parseDouble(nums[j]);
        }
    }

    s.close();

You can try removing the whitespace with line.trim() after line = s.nextLine() as a work-around. Trim removes leading and trailing whitespace, so it shouldn't interfere with the delimiters for .split() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM