user985668
user985668

Reputation:

Why does the program ouput correct if dimensions create a square but not a rectangle?

I'm writing a program where I need to make a hollow box of asterixs'. The program works fine when I enter dimensions for a square but it doesn't work when I enter dimensions for a rectangle.

import java.util.Scanner;
public class asterix {
    public static void main(String[] args) { 

    Scanner input = new Scanner( System.in );

 int stars; // length of side
 int column; // width of box
 int row = 1;

// prompt user to enter the length and width of box

 System.out.print("Enter the length: ");
 stars = input.nextInt();

 System.out.print("Enter the width: ");
 column = input.nextInt();



 while ( row <= stars ) {
     column = 1;

 // and for as many columns as rows 
while ( column <= stars ) {

    if ( row == 1)
    System.out.print( "*" );

    else if ( row == stars )
    System.out.print( "*" );

    else if ( column == 1 )
    System.out.print( "*" );

    else if ( column == stars )
    System.out.print( "*" );

    else
    System.out.print( " " );

column++; } // end inner while loop

System.out.println();
 row++;


      } // end output
    } // end of main
} // end of Stars

The ideal output I would want is as follows:

Say its 3 by 3:

   ***
   * *
   ***

and say its 4 by 3:

   ****
   *  * 
   ****

Upvotes: 0

Views: 346

Answers (2)

Joachim Sauer
Joachim Sauer

Reputation: 308021

column and row represent your current coordinates (seeing as they are modified in the loop).

In the beginning you read the user input into stars and column, so those should represent the maximum number.

As you notice there is some overlap. You need to define column to mean either the current location or the maximum amount of columns and define a new variable for the other meaning.

This shows how important it is to have meaningful names, even if they are longer. If you had named your variables maxColumns, maxRows and currentColumn, currentRow then the problem would have been very visible.

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258568

You need to modify the following lines.

System.out.print("Enter the width: ");
int numberOfColumns = input.nextInt();

and

while ( column <= numberOfColumns )

You compare both loops to the number of lines, and therefore get a square. You should use the number of columns in your inner-loop.

I'm sure it's just a slip-up, you would have caught it.

Upvotes: 1

Related Questions