DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

+ Reply to Thread
Results 1 to 2 of 2
  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!

Bookmarks

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


Top DevX Stories

Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL


Sponsored Links