Advertisement
steynvl

Java read matrix

Jan 19th, 2018
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.37 KB | None | 0 0
  1. import java.io.File;
  2. import java.io.FileNotFoundException;
  3. import java.util.Scanner;
  4.  
  5. public class Matrix {
  6.  
  7.     public static void main(String[] args) {
  8.  
  9.         if (args.length != 1) {
  10.             System.err.println("Usage: java Matrix <matrix.txt>");
  11.             System.exit(1);
  12.         }
  13.  
  14.         String matrix[][] = new String[10][10];
  15.         Scanner scanner = null;
  16.  
  17.         try {
  18.  
  19.             scanner = new Scanner(new File(args[0]));
  20.             int lineNr = 0;
  21.  
  22.             while (scanner.hasNext()) {
  23.  
  24.                 String[] line = scanner.nextLine().split(" ");
  25.                 for (int col = 0; col < line.length; col++) {
  26.                     matrix[lineNr][col] = line[col];
  27.                 }
  28.                 lineNr++;
  29.  
  30.             }
  31.  
  32.         } catch (FileNotFoundException e) {
  33.             e.printStackTrace();
  34.         } finally {
  35.             assert scanner != null;
  36.             scanner.close();
  37.         }
  38.  
  39.         printMatrix(matrix);
  40.  
  41.     }
  42.  
  43.     private static void printMatrix(String[][] matrix) {
  44.  
  45.         for (String[] aMatrix : matrix) {
  46.             for (int col = 0; col < aMatrix.length; col++) {
  47.                 System.out.print(aMatrix[col]);
  48.                 if (col != aMatrix.length - 1) {
  49.                     System.out.print(" ");
  50.                 }
  51.             }
  52.             System.out.println();
  53.         }
  54.  
  55.     }
  56.  
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement