这个任务,我们的老师让我们扭动我们的大脑一点(如果我们想)是创建一个程序,输出只是一个矩形的周长。到目前为止,我编写的代码给出了正确的维度,但左侧内部只有一个不需要的空间。例如,如果输入维度是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();
}
}
}发布于 2014-03-28 09:32:43
将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();
}https://stackoverflow.com/questions/22708617
复制相似问题