Mike Goedken Mike Goedken - 2 months ago 6
Java Question

Format help in JAVA

How can I add the last print line to also be at the beginning so when it prints it looks like a rectangle?

Scanner stdin = new Scanner(System.in);

System.out.println("Enter number of rows and columns: ");
int row = stdin.nextInt();
int column = stdin.nextInt();
int m = 1;
int k = 1;

while(m <= column)
{

while(k <= row)
{
System.out.print("* *\n");
k++;
}

System.out.print("*");
m++;
}

Answer

You're really close, just re-use your loop that creates the last line at the beginning:

Scanner stdin = new Scanner(System.in);

        System.out.println("Enter number of rows and columns: ");
        int row = stdin.nextInt();
        int column = stdin.nextInt();
        int m = 1;
        int k = 1;

        while(m <= column)         // Add
        {                          //
            System.out.print("*"); // these 
            m++;                   //
        }                          // lines
        System.out.print("\n");    //
        m=1;                       // then reset m
        while(m <= column)
        {
            while(k <= row)
            {
                System.out.print("*   *\n");
                k++;
            }

            System.out.print("*");
            m++;
        }