Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;

import java.util.Scanner;

public class Main {
    public static float[][] readMatrix(String path) throws FileNotFoundException {
        int n = 0, p = 0;
        System.err.println("Load matrix from " + path);
        Scanner sc = new Scanner(new BufferedReader(new FileReader(path)));
        while (sc.hasNext()) {
            String line = sc.nextLine();
            if (line.startsWith("%")) {
                System.err.println(line);
            } else {
                String[] dim = line.split(" ");
                n = Integer.parseInt(dim[0]);
                p = Integer.parseInt(dim[1]);
                System.err.println("num rows: " + n + "\n" + "num cols: " + p);
                break;
            }
        }
        int count = 0;
        float[][] mat = new float[p][n];
        int row = 0, col = 0;
        while (sc.hasNextLine()) {
            String line = sc.nextLine();
            if (line.isEmpty()) {
                break;
            }
            Float val = Float.parseFloat(line);
            mat[col][row] = val;
            row++;
            if (row == n) {
                row = 0;
                col++;
            }
            count++;
        }
        if (count != n * p) {
            System.err.println("Parse fail: not enough elements. num rows: " + n + "\n" + "num cols: " + p
                    + "\n nun elements: " + count);
            return null;
        }
        System.err.println("Done.");
        return mat;
    }
}