Rectangle program


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 2 of 2

Thread: Rectangle program

  1. #1
    Join Date
    Oct 2002
    Posts
    15

    Rectangle program

    Hi i need to write a program that asks the user for the length and width of a rectangle, and must print the rectangle using *'s .... for example a width of 5 and length of 7

    * * * * * * *
    * *
    * *
    * *
    * *
    * *
    * * * * * * * ...


    i have the program all set,,, but the right side does not print properly, unless i put 5x7 for the width and length... other values print incorrect......
    here is my code:

    /*

    import java.io.*;

    public class Class1
    {
    public static void main(String[] args) throws IOException
    {

    BufferedReader IN= new BufferedReader(new InputStreamReader(System.in));
    System.out.print(" what is the width >");
    int width=Integer.parseInt(IN.readLine());

    System.out.print(" what is the length >");
    int length=Integer.parseInt(IN.readLine());

    if(width<=0)
    {
    System.out.print(" Invalid amount!");
    }
    else if(length<=0)
    {
    System.out.print(" Invalid amount!");
    }


    System.out.println();
    System.out.println();

    //top length of rectangle
    int count=0;
    while(length>count)
    {

    System.out.print(" * ");
    count+=1;
    }
    //left side
    count=1;
    int next=0;
    System.out.println();
    int length2=(length*2)+2;
    while(width>count)
    {
    System.out.print(" *");
    //right=length*2)
    while(length2>next)
    {
    System.out.print(" ");

    next+=1;

    }
    System.out.print(" *");
    System.out.println();
    count+=1;
    next=0;
    }


    // bottom
    count=0;
    while(length>count)
    {

    System.out.print(" * ");
    count+=1;
    }


    System.in.read();
    }


    }

    */

  2. #2
    Join Date
    Nov 2002
    Posts
    59
    I've actually done this same exercise before, and for me, it was much easier to use a nested for loop. For example:

    for (int a = 0; a<length; a++) {
    for (int i = 0; a < width; a++) {
    System.out.print("*");
    }
    System.out.println("");
    }

    I was unable to find the problem with your code, so that's why I did this...plus it's much cleaner. Hope it helps!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center