import java.util.*; class MatrixStdIO { MatrixStdIO(String args[]) { int i, j; Scanner console = new Scanner(System.in); Scanner lineTokenizer; int [][] matrix; int numRows; String inputLine; // read the first line so we can determine the dimensions // of the matrix inputLine = console.nextLine(); // there is no way to query a Scanner object to determine the // number of tokens it holds so I am using the String class's // split() method to split the strings based on white space. // The "\\s+" represents a regular expression where the first // \ deferences the second \ and the \s+ means the split // delimiter is one or more white spaces. These are perl style // regular expressions and you will learn more about them when // we cover scripting languages numRows = inputLine.split("\\s+").length; matrix = new int[numRows][numRows]; // fill in the first row of the matrix lineTokenizer = new Scanner(inputLine); for (j = 0; j < numRows; j++) { matrix[0][j] = lineTokenizer.nextInt(); } lineTokenizer.close(); // fill in the remaining rows of the matrix. I am not doing any // error checking. for (i = 1; i < numRows; i++) { inputLine = console.nextLine(); lineTokenizer = new Scanner(inputLine); for (j = 0; j < numRows; j++) { matrix[i][j] = lineTokenizer.nextInt(); } lineTokenizer.close(); } // print the matrix for (i = 0; i < numRows; i++) { for (j = 0; j < numRows; j++) { System.out.printf("%4d", matrix[i][j]); } System.out.printf("%n"); } } static public void main(String args[]) { new MatrixStdIO(args); } }