Search code examples
javaarraysmultidimensional-arrayuser-input

How to set elements in a matrix to blank " ", instead of default "null"


I have the following code, and I would like the user inputs to store, and then the code loop back with the next input storing also, until they hit "Q" which will then quit. I am not sure how to do it. Also, I want my 2d array to be printed blank, instead of the default 0s, after the user sets the size. SO if the user says they want to input SIZE = 4x4 "row =1, column =2, input =7" it would print "These ZEROS would be BLANK

0000
0070
0000
0000

the input "row 2, column 1, input A it would print

0000
0070
0700
0000

My code so far

import java.util.*;

public class MainProg {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.print("How many rows do you want for your matrix?  ");
        int row = in.nextInt();

        System.out.print("How many columns do you want for your matrix?  ");
        int column = in.nextInt();
        String[][] newArray = new String[row][column];


        Array2 twoDArray = new Array2(row, column, newArray); //calling my class


        do {
            System.out.println("If you would like to set an, element press S: " + "\n" +
                    "If you would like to set an element, press G" + "\n" +
                    "If you would like to empty an element, press E" + "\n" +
                    "If you would like to print an element, press P" + "\n" +
                    "If you would like to quit, press Q");
            String userInput = in.next();


            if (userInput.equalsIgnoreCase("S")) {
                twoDArray.setElement();
            } else if (userInput.equalsIgnoreCase("G")) {
                twoDArray.getElement();
            } else if (userInput.equalsIgnoreCase("E")) {
                twoDArray.clearElement();
            } else if (userInput.equalsIgnoreCase("P")) {
                twoDArray.printMatrix();
                //you will do you toString here
            } else if (userInput.equalsIgnoreCase("Q")) {
                //this will quit the program
                twoDArray.quitProgram();
            }
            //break;
        } while (true);
    }
}
import java.util.*;

public class Array2 {
    MainProg main1 = new MainProg();
    Scanner in = new Scanner(System.in);
    private String [][] newArray;
    private int row;
    private int column;



    public Array2(int row, int column, String[][] newArray) {
        this.row = row;
        this.column = column;
        this.newArray = newArray;
    }

    public void getElement() {
        Scanner in = new Scanner(System.in);
        System.out.println("What row is the element you would like to get in? (Must be under " + row + ")");
        int userRow = in.nextInt();
        System.out.println("What column is the element you like to get in? (Must be under " + column + ")");
        int userCol = in.nextInt();
        System.out.println("You have entered: " + "\n" +
                "Row " + userRow + "\n" +
                "Column " + userCol);
        String getElement = newArray[userRow-1][userCol-1];
        System.out.println(getElement);
    }

    public void setElement() {
        System.out.println("What row would you like your element in? (Must be under " + row + ")");
        int userRow = in.nextInt();
        System.out.println("What column would you like your element in? (Must be under " + column + ")");
        int userCol = in.nextInt();
        System.out.println("What character would you like the element to be?");
        String userChar = in.next();
        System.out.println("You have entered: " + "\n" +
                "Row " + userRow + "\n" +
                "Column " + userCol + "\n" +
                "Char to be entered: " + userChar);
        newArray[userRow][userCol] = String.valueOf(userChar);
    }

    public void clearElement() {
        Scanner in = new Scanner(System.in);
        System.out.println("What row is the element you would like empty? (Must be under " + row + ")");
        int userRow = in.nextInt();
        System.out.println("What column is the element you like to empty? (Must be under " + column + ")");
        int userCol = in.nextInt();
        System.out.println("You have entered: " + "\n" +
                "Row " + userRow + "\n" +
                "Column " + userCol);

    }

    public void printMatrix() {
        Scanner in = new Scanner(System.in);
        //String result = " ";
        System.out.println("The array is: \n");
        for (int i = 0; i < newArray.length; i++) {
            for (int j = 0; j < newArray[i].length; j++) {
                System.out.print(newArray[i][j]);
            }
            //for (String[] row: newArray) THIS LEAD TO A PROBLEM
            //    Arrays.fill(row, " ");
            System.out.println();
        }
    }

    public void quitProgram() {
        System.out.println("The system will now exit! BYE!!!");
        System.exit(0);
    }
}

I have EDITED my code so that I have answered some questions. Now my only problem left is getting my matrix to be initially filled with blanks " ", instead of the default "null". I attempted to use the Arrays.fill in my printMatrix method, however that lead to problems, it would not save the user input after the loop.


Solution

  • Your IndexOutOfBoundsException (now editted out) is due to you using row and column instead of userRow and userColumn in setElement, which are where you've stored the user inputs. row and column will refer to the classes member variables, which are both 5 since you set it up as a 5x5 matrix, so above the max index of 4. You also will need to conver the char to a string since your using a String[][]

    System.out.println("You have entered: " + "\n" +
            "Row " + userRow + "\n" +
            "Column " + userCol + "\n" +
            "Char to be entered: " + userChar);
    newArray[row][column] = userChar;
    

    The last line should be newArray[userRow][userColumn] = String.valueOf(userChar);. Though you probably want to check those values are less than row and column to avoid more of that exception.

    Even with that fixed, your code currently has other issues. The biggest is that you're currently defininig and using a new array in most methods and not the member variable newArray, so the method calls to get/set/clear/print aren't using your instance like you expect, but new empty arrays each time. These should be manipulating this.newArray not creating their own to manipulate, which dies with their return. You'll need to work through fixing all of that before looking into looping over the user input and interacting with your array.

    On the printing of 0's, that is a side affect of one of the above issues. In printMatrix you declare a new int[][] newArray and print that. The default value of int is 0, so you get all 0's. If you were using your String array you'd get all "nullnullnull.." for each row as String's default to null. If you want all blanks initially, you'll have to initalize the array to all empty strings in your constructor or handle the null when looping through the array printing a space instead.

    On looping for user input, you'll also need to ask for it again inside of your loop before the while, as otherwise the user input will only be asked for once and you will forever loop with that option.

    Good luck, this seems like a good excersize to familiarize yourself with OO and array maniupulation, but a lot of the issues in your code are outside the scope of a single SO answer and smells a bit like classwork. I got your example code fixed up and manipulating as you want with only a handful of changes, so you're close.

    Here's a few more bits of advice based on your comments and edits.

    If you want to prefill the rows with spaces, the

    for (String[] row : newArray)
        Arrays.fill(row, " ");
    

    block of code would not go in print, as that would blank it out each time print is called. It should go into your constructor, so that it only happens once when the object is created.

    Alternatively, if you wanted to deal with it in the print method, something like

    System.out.print(newArray[i][j] == null ? " " : newArray[i][j]);
    

    Would do the trick, using a ternary operator to print out " " instead of null when encountered.

    You also don't need to new up the Scanner in those methods but its not affecting functionality.