用于在Java中输出矩形周长的循环
我们的老师让我们稍微绞尽脑汁(如果我们愿意的话)的任务是创建一个只输出矩形周长的程序。到目前为止,我编写的代码给出了正确的尺寸,但左内侧得到了一个不需要的空间。例如,如果输入尺寸为高度=4宽度=5生成器=x(在代码之前列出)。这项任务根本不值一分。如果有人能帮我解决这个问题,这样它就不会再逗我的大脑了;我将不胜感激用于在Java中输出矩形周长的循环,java,Java,我们的老师让我们稍微绞尽脑汁(如果我们愿意的话)的任务是创建一个只输出矩形周长的程序。到目前为止,我编写的代码给出了正确的尺寸,但左内侧得到了一个不需要的空间。例如,如果输入尺寸为高度=4宽度=5生成器=x(在代码之前列出)。这项任务根本不值一分。如果有人能帮我解决这个问题,这样它就不会再逗我的大脑了;我将不胜感激 xxxxx x x x x xxxxx /* Creating rectangle */ import javax.swing.JOptionPane; public c
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();
}
}
}
xxxxx
x x
x x
xxxxx
/*
创建矩形
*/
导入javax.swing.JOptionPane;
公共类矩形
{
公共静态void main(字符串参数[])
{
//声明变量
字符串宽度字符串;
弦高弦;
字符串生成器;
整数宽度;
内部高度;
整数宽度计数器;
内部高度计数器;
//输入尺寸和生成器
heightString=JOptionPane.showInputDialog(“请输入高度”);
widthString=JOptionPane.showInputDialog(“请输入宽度”);
builder=JOptionPane.showInputDialog(“请输入建筑字符”);
//解析维度
高度=整数.parseInt(高度字符串);
宽度=整数.parseInt(宽度字符串);
对于(heightCounter=0;heightCounter将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();
}
for(heightCounter=0;heightCounter=1&&widthCounter
首先看一下如果(heightCounter>=1&&heightCounter!=height-1)
有条件。当height=4
和heightCounter=1
时会发生什么?嗯,我想我有点接近了。这样做更有意义。谢谢!