for循环在Java中输出矩形的周长

时间:2014-03-28 09:21:33

标签: java

我们的导师告诉我们这个任务让我们大脑(如果我们想要的话)创建一个只输出矩形周长的程序。到目前为止我写的代码给了我正确的尺寸,但内部左侧获得了一个不需要的空间。例如,如果输入尺寸为height = 4 width = 5 builder = x(在代码之前列出如下)。这项任务甚至不值得任何一点。如果有人能帮助我解决这个问题,我就会停止戏弄我的大脑;我将不胜感激。

xxxxx
 x  x
 x  x
xxxxx

/*
Creating rectangle
*/
import javax.swing.JOptionPane; 
public class rectangle
{
   public static void main(String args[])
   { 
     // Declare variables
     String widthString;
     String heightString;
     String builder;
     int width;
     int height;
     int widthCounter;
     int heightCounter;
     //Inputing dimensions and builder
     heightString=JOptionPane.showInputDialog("Please enter height");
     widthString=JOptionPane.showInputDialog("Please enter width");
     builder=JOptionPane.showInputDialog("Please enter building character");
     //Parsing dimensions
     height=Integer.parseInt(heightString);
     width=Integer.parseInt(widthString);

     for(heightCounter=0; heightCounter<height; heightCounter++)
         {
         for(widthCounter=0; widthCounter<width-2; widthCounter++)
               {
               if(heightCounter==0||heightCounter==height-1)
                  System.out.print(builder);
               if(heightCounter>=1&&heightCounter!=height-1)
                  System.out.print(" ");           
               if(widthCounter==0||widthCounter==width-3)
                  System.out.print(builder);

               }               


         System.out.println();      
         }

   }
}

1 个答案:

答案 0 :(得分:1)

将下面的for循环替换为

    for (heightCounter = 0; heightCounter < height; heightCounter++) {
        for (widthCounter = 0; widthCounter < width; widthCounter++) {
            if (heightCounter == 0 || heightCounter == height - 1)
                System.out.print(builder);
            else if (widthCounter >= 1 && widthCounter < width - 1) //Use widthCounter instead of heightCounter here
                System.out.print(" ");
            else
                System.out.print(builder);
        }

        System.out.println();
    }