首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Java中循环输出矩形的周长

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

Stack Overflow用户
提问于 2014-03-28 09:21:33
回答 1查看 703关注 0票数 0

这个任务,我们的老师让我们扭动我们的大脑一点(如果我们想)是创建一个程序,输出只是一个矩形的周长。到目前为止,我编写的代码给出了正确的维度,但左侧内部只有一个不需要的空间。例如,如果输入维度是height=4 width=5 builder=x (在代码之前列出)。这项任务甚至不值一分钱。如果有人能帮我解决这个问题,那么我就不会再取笑我的大脑了,我会非常感激的。

代码语言:javascript
复制
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();      
         }

   }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-03-28 09:32:43

for循环替换为下面,

代码语言:javascript
复制
    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();
    }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22708617

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档