andzrev
andzrev

Reputation: 564

Java - Printing an empty square using nested loops

I am working on printing a quasi-empty square that looks like the example below (10 asterisks across and 10 down for the 2 columns):

**********
*        *
*        *
*        *
*        *
*        *
*        *
*        *
*        *
**********

My code cannot dynamically generate squares as specified by the user's input for the number of rows and columns (it is working for 10 rows and 10 columns, but as soon as I change the number to 20, the number of the asterisks does not change. The following is my code:

String STAR = "*";
String star1 = "**********";
int MAX = 10;
for (int row = 0; row <= MAX; row += 1 ) {
    for (int col = 0; col <= MAX ; col += 10) {
        if (row == 0 && col == 0)
            System.out.println(star1);
        if (row >= 1 && row <= 4)
            System.out.println(STAR + "        " + STAR);
        if (row == 10 && col == 10)
            System.out.println(star1);
    }
}

Any help/advice is welcomed regarding the dynamism of the code.

Upvotes: 1

Views: 33508

Answers (16)

Hassan Khan
Hassan Khan

Reputation: 1

I am hopeful the code below can help, used very simple coding and have the required result.

a=eval(input('Provide the height of the box: '))
b=eval(input('Provide the width of the box: '))
d=a-2
r=b-2

if a >= 1:
   print('*'*b)
if a > 1:
   for i in range(d):
       print('*',end='')
       for i in range(r):
           print(' ',end='')
       print('*')
   print('*'*b,end='')

The result is:
The following result is for the height: 6 and width:15

Upvotes: -1

Shubham
Shubham

Reputation: 1

import java.util.Scanner;
class Star
{
    public static void main(String...args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the row : ");
        int row=sc.nextInt();
        System.out.print("Enter the column : ");
        int column=sc.nextInt();
        for(int i=1;i<=column;i++)
        {
            System.out.print("*");
        }
        for(int i=row-2;i>=1;i--)
        {
            System.out.println();
            System.out.print("*");
            for(int k=1;k<=column-2;k++)
            {
                if(i<1)
            {
                break;
            }
                System.out.print(" ");

            }
            System.out.print("*");
        }
        System.out.println();
        for(int i=1;i<=column;i++)
        {
            System.out.print("*");
        }
    }
}

Upvotes: 0

Jorick Caberio
Jorick Caberio

Reputation: 205

Here's another solution, a more versatile one. It lets you create a hollow rectangle of height "h" and width "w"

     private static void hallowSquare(int h, int w)
{
    for(int i=1; i<=h; i++)
    {
        for(int j=1; j<=w; j++)
        {
            if (j==1|| j==w || i==1 || i==h )
            System.out.print("X");
            else
                System.out.print(" ");
        }
        System.out.println();
    }

}

Upvotes: 0

Stuti Bisht
Stuti Bisht

Reputation: 1

you can use below two methods.

1) One with minimal line of code.

for (int i = 0; i <= 9; i++) {
            if (i == 0 || i == 9) {
                System.out.println("* * * *");
            } else {
                System.out.println("*     *");
            }
        }

OR

2) With the help of two for loops

for (int i = 0; i <= 9; i++) {
                for (int j = 0; j <= 9; j++) {
                    if (i == 0 || i == 9) {
                        System.out.print("*");
                    } else {
                        if (j == 0 || j == 9) {
                            System.out.print("*");
                        } else {
                            System.out.print(" ");
                        }
                    }
                }
                System.out.println();
            }

Thanks, Stuti

Upvotes: 0

John Quasar
John Quasar

Reputation: 196

This code should do the trick.

package javaPackage;

public class Square {   

    public static void main(String [] args)
    {
        for (int i=0;i<=10;i++)
        {
            for (int j=0;j<=10;j++)
            {
                if(i==0||i==10){
                    System.out.print("x");
                }
                else if(j==0||j==10){
                    System.out.print("x");
                }
                else{
                    System.out.print(" ");
                }
            }
            System.out.println();
        }
    }
}

If the interpreter sees that you're on the first and last line(i=0 and i=10), it will fill the row with x. Else, it will only print a x at the beginning and the end of the row.

Upvotes: 0

govind shaw
govind shaw

Reputation: 1

class  square1
  {
     public static void main(String[] args) 
      {
       String star = "*";
       String space = " ";
       int MAX = 5;
      for (int row = 0; row < MAX; row++) 
        {
          for (int col = 0; col < MAX; col++) 
            {
             if (row == 0 || row == MAX - 1) 
              {
                System.out.print(star);
              } else if (col == 0 || col == MAX - 1)
              {
                System.out.print(star);
              } else {
               System.out.print(space);
              }
          }
        System.out.println();
        }
     }
   }

Upvotes: 0

H.B
H.B

Reputation: 107

Hope this helps, simplify your thinking mate. Think about the axis x and y and work by that logic. Make a nested loop on ur for loop that passes lines, in each case loop the number of the size of square and print a space, after the nested loop print the "*".

> for (int b=0;b<ans*2-3;b++)

This nested loop has the max value of b because:

remember that while ur printing, each "*" is distanced from the other by a space, and remember u are only counting space between the first and last column. Meaning all space between x=0 and x=squaresize, therefore max b should be the space between these 2 coords. which are: squaresize * 2 /the 2 is for the added spaces/ -3/* -3 because u leave out the first coord(x=0),last coord(x=squaresize), AND 1 space added from the former loop.

import java.util.Scanner;
public class AsteriksSquare {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner input= new Scanner(System.in);
        int ans;
        System.out.print("Enter the size of the side of the square: ");
        ans=input.nextInt();
        String ast="*";
        if (ans>0 && ans<21){

            for(int i=0;i<=ans-1;i++){
                System.out.print("* ");


        }
            System.out.println("");
            for(int i=1;i<=ans-2;i++){
                System.out.print("*");
                for (int b=0;b<ans*2-3;b++){
                    System.out.print(" ");

                }
                System.out.println("*");


        }
            for(int i=1;i<=ans;i++){
                System.out.print("* ");


        }

}
}
}

Upvotes: 0

KISHOR KUNAL
KISHOR KUNAL

Reputation: 1

class Star8
{
    public static void main(String[] args) 
    {
        for(int i=1;i<=5;i++)
        {
            for(int j=1;j<=5;j++)
            {
                if(i==2||i==3||i==4 )
                {
                    System.out.print("*    *");
                    break;
                }
                else
                {
                    System.out.print("*");
                }
            }    
            System.out.println();
         }
     }
 }

Upvotes: 0

Zuhair Sagga
Zuhair Sagga

Reputation: 301

you can use something like this with one user input ... this is working

public static void drawSquare(int size)
{
       for(int i=1; i<size ;i++)
       System.out.print("*");
       System.out.println("");
       for(int i=0; i<50 ;i++)
       {
              System.out.print("*");
              for(int j =0; j<size-3; j++)
                    System.out.print(" ");
              System.out.println("*");
       }

       for(int i=1; i<size ;i++)
              System.out.print("*");
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    drawSquare(50);
}

you should just create a class in put this inside your class and run it ... I hope this will help you ....

Upvotes: 0

Jorick Caberio
Jorick Caberio

Reputation: 205

this should work

    public static void hallowSquare(int side)
{
    int rowPos, size = side;

    while (side > 0)
    {

        rowPos = size;

        while (rowPos > 0)
        {

            if (size == side || side == 1 || rowPos == 1 || rowPos == size)
                System.out.print("*");

            else
                System.out.print(" ");
            rowPos--;
        }
        System.out.println();
        side--;

    }       

}

Upvotes: 0

anonymous
anonymous

Reputation: 1

class Square 
{

    public static void main(String[] args) 
    {
        String tenStars="**********";
        String oneStar="*";
        int count=0;

        System.out.println(tenStars);
        count++;
        while(count<=8)
        {
            System.out.println(oneStar+"     "+oneStar);
            count++;
        }
        System.out.print(tenStars);

    }
}

Upvotes: 0

Tyler Stennette
Tyler Stennette

Reputation: 53

Like mentioned above, the nested for loop is unnecessary and can be inefficient if you plan to create larger rectangles in the future (not saying you're going to have to but try to stay away from nested for loops if you can). Instead, just print star1 before your loop begins and after it exits. The body of the loop should be simple enough. Hope this helps.

Upvotes: 0

Churk
Churk

Reputation: 4637

String star = "*";
String space = " ";

int MAX = xxx;

for (int row = 0; row < MAX; row++) {
  for (int col = 0; col < MAX; col++) {
    if (row == 0 || row == MAX - 1) {
      System.out.println(star);
    } else if (col == 0 || col == MAX - 1) {
      System.out.println(star);
    } else {
      System.out.println(space);
    }
  }
}

Upvotes: 2

Aurora
Aurora

Reputation: 4414

Also take a look at your last if statement there where it says if (row == 10 && col == 10) and think about it for a second. Once you have hit 10 rows and 10 columns, you are just going to print your final horizontal line of star1 regardless of what MAX is set too.

Upvotes: 0

talnicolas
talnicolas

Reputation: 14053

You should change the 3 occurrences of 10 in your two for loops by the MAX variable, so when the user define another size, your for loop will take his input instead of the 10 value.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503489

Look at your nested loop:

for (int col = 0; col <= MAX ; col += 10) {

So when col is 10, you're really only just iterating once... you might as well not have the nested loop at all.

Additionally, both star1 and the string literal with spaces have a fixed number of characters in them, clearly related to the number of columns.

I'm assuming this is homework, so I won't give any more hints than that to start with, but hopefully that'll get you thinking along the right lines...

Upvotes: 0

Related Questions