Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class Matrix {
- public static void main(String[] args) {
- Scanner scan = new Scanner(System.in);
- System.out.println("Welcome to the Matrix Maker");
- System.out.println("=============================");
- System.out.println("\nHere are your options:");
- System.out.println("1 \t To enter matrix data" +
- "\n2 \t To display matrix" +
- "\n3 \t To exit\n");
- System.out.print("Enter your option here: ");
- int choiceMade = Integer.parseInt(scan.nextLine());
- int[][] yourMatrix = new int[0][0];
- switch(choiceMade) {
- case 1:
- int matrixRow = getRows(scan);
- int matrixCol = getCols(scan);
- yourMatrix = new int[matrixRow][matrixCol];
- enterMatrixData(scan, yourMatrix);
- case 2:
- printMatrix(yourMatrix);
- break;
- case 3:
- System.out.println("Goodbye!");
- System.exit(0);
- default:
- System.out.println("Invalid choice!");
- }
- }
- public static int getRows(Scanner s) {
- System.out.print("Enter the number of matrix rows: ");
- int row = Integer.parseInt(s.nextLine());
- while (row <= 0) {
- System.out.print("Enter the number Of matrix rows: ");
- row = Integer.parseInt(s.nextLine());
- }
- return row;
- }
- public static int getCols(Scanner s) {
- System.out.print("Enter the number of matrix columns: ");
- int cols = s.nextInt();
- while (cols <= 0) {
- System.out.print("Enter the number Of matrix rows: ");
- cols = Integer.parseInt(s.nextLine());
- }
- return cols;
- }
- public static void enterMatrixData(Scanner s, int[][] m) {
- for (int i = 0; i < m.length; i++) {
- for (int j = 0; j < m[i].length; j++) {
- System.out.printf("Enter value for Row %,d, Column %,d: ", i+1, j+1);
- m[i][j] = s.nextInt();
- }
- }
- }
- public static void printMatrix(int[][] matrix) {
- if (matrix.length == 0) {
- System.out.println("Matrix is empty!");
- } else {
- for (int[] rowVals : matrix) {
- for (int colVals : rowVals) {
- System.out.print(colVals + "\t");
- }
- System.out.println();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment