javaloopsmethodsconditional-statements

How can I make a grid using " | " and " _ " on java?


I'm a beginner at Java, and my programming teacher gave us an assignment that we need to make a grid of little squares using "|" and "_". Assignment

I know this might look stupid, but it was the best that I could do. I managed to make the columns, but now I don't know how to make the rows.

package practice;

public class practice {
    
    public static void main (String[] args) {
    
    squares(4);
        
    }
    
    
    public static void squares(int number) {
        for (int i=0; i<number; i++) {
        System.out.print(" _");
        }
            System.out.println();
    
        for (int i=0; i<number; i++) {
        System.out.print("|_");
        }
            System.out.print("|");
            System.out.println();
    
    }
    
}

Until now I have learned how to use conditionals and loops, and this assignment is about using methods.


Solution

  • This should do what you want it to. Use java.util.Scanner to get the input of the user for the number of rows and the number of columns. Then print the squares with some for-loops. If you are concerned about efficiency use StringBuilder instead, but I didn't use it here to keep it simple.

    import java.util.Scanner;
    
    public class Practice {
        public static void main(String[] args) {
            printGrid();
        }
    
        public static void printGrid() {
            // get input
            Scanner scanner = new Scanner(System.in);
            System.out.println("Enter rows");
            int rows = scanner.nextInt();
            System.out.println("Enter columns");
            int cols = scanner.nextInt();
            scanner.close()
    
            // print top line
            if (rows > 0) {
                System.out.print(" ");  // padding
                for (int i = 0; i < cols; i++) {
                    System.out.print("_ ");
                }
                System.out.println();  // new line
            }
            for (int i = 0; i < rows; i++) {
                // print left line
                System.out.print("|");
                for (int j = 0; j < cols; j++) {
                    System.out.print("_|");
                }
                System.out.println();  // new line
            }
        }
    }