java - 矩形程序不准确
问题描述
我正在尝试制作一个程序,它将询问用户矩形的长度和宽度,其中长度和宽度将用 * 符号描绘。该程序实际上运行良好,它只是添加了一个额外的符号,我这样做了不知道为什么。
例如,我输入 5 作为长度,输入 4 作为宽度,我的输出最终将如下所示:
xxxxxx
x x
x x
x x
xxxxxx
我上面的这些尺寸实际上是 6x5,即使我在程序中放了 5x4。
我希望程序看起来像这样,预期输出:
xxxxx
x x
x x
xxxxx
我的代码是:
import java.util.Scanner;
public class aps{
public static void main(String [] args){
//Declaring variables
int length, width;
//Prompting user for length
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the length of your rectangle: ");
length = scanner.nextInt();// integer i for rows(width)
//Prompting user for width
System.out.print("Enter the width of your rectangle: ");
width = scanner.nextInt();//integer j for columns(length)
//Processing
for(int i = 0; i<=width; i++){ //first loop
for(int j = 0; j<=length; j++){ //second loop
if(i==0||j==0||j==length||i==width){
System.out.print("*");
}
else{
System.out.print(" ");
}
}// end of second loop
System.out.println();
} //end of first loop
}
}
解决方案
如果您希望 for 循环运行某些n
时间,则需要 for 循环采用形式for(int i=0; i < n; i++)
或for(int i=1; i <= n; i++)
代替for(int i=0; i <= n; i++)
,它运行n+1
时间(即一次为 0,然后n
从 开始1..n
)。
一个简单的解决方法是在 for 循环条件中更改<=
to <
,以及更改if
条件以反映更改:
import java.util.Scanner;
public class aps{
public static void main(String [] args){
//Declaring variables
int length, width;
//Prompting user for length
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the length of your rectangle: ");
length = scanner.nextInt();// integer i for rows(width)
//Prompting user for width
System.out.print("Enter the width of your rectangle: ");
width = scanner.nextInt();//integer j for columns(length)
//Processing
for(int i = 0; i<width; i++){ //first loop
for(int j = 0; j<length; j++){ //second loop
if(i==0||j==0||j==length-1||i==width-1){
System.out.print("*");
}
else{
System.out.print(" ");
}
}// end of second loop
System.out.println();
} //end of first loop
}
}
推荐阅读
- ios - 在 SDAnimatedImageView 中重复源图像
- java - 当从匿名内部类或 lambda 访问时,为什么数组的值被视为最终或“有效最终”?
- spring-boot - Kotlin 使用 slf4j 进行日志记录的最佳方式
- python - 如何在熊猫的任何过滤列中获取值至少匹配一次的行
- angular - 如何在 Angular 中将正文添加到 HTTP GET 请求
- sql - 如何检查特定属性的元素是否存在于列中?
- python - 在 Python 中提取 XML 标记并保留标记顺序和层次结构
- java - 无论如何,switch case语句是否只计算小于分配的值?
- python - 我怎样才能加快这种方法?
- sql - 在每个月的第一天获取列的最新值