如何使用两个for循环做空心的盒子 [英] How to make hollow box using two for loops
问题描述
使用嵌套的for循环语句来绘制*的圣诞框。这些框具有相同数量的行和列,并且该数字应该从用户输入(有效范围:5到21)。我有麻烦想出一个方法来使箱子空心。这是我的代码,它来作为一个完整的广场,但我需要它是空心或只是边界。
System.out.println(多少行/列(5-21)?);
rows = input.nextInt();
while(rows <5 || rows> 21){
System.out.println(Out of range。Reenter:);
rows = input.nextInt(); (m = 1; m <=行; m ++){
(c = 1; c <=行; c ++){
System.out.print ( *);
}
System.out.println();
输出应该如下所示:
有多少行/列(5-21)? 25
超出范围。重新输入:7
*******
* *
* *
* *
* *
* *
*******
* s,所以在之前添加一个测试,打印( *)
。一个选项是明确地测试四个条件(顶部,底部,左,右),并将它们逻辑地结合在一起:
if ((m == 1)|| // top
(m == rows)|| // bottom
(c == 1)|| // left
(c ==行)//右
){
System.out.print(*);
} else {
System.out.print();
每个 m ==
test或 c ==
测试标识一块正方形。由于四个测试
进行OR运算,如果四个测试中的任何一个都为真,则if()为真(并打印一个*)。如果它们都不是真的,那么 else
会运行并打印一个空格。我还建议重命名 m
到 rowIndex
和 c
到 colIndex
什么的。当你一两个星期后再回到代码时,更多的描述性名字将使你更容易从中断的地方继续。 (问我怎么知道!)
Use nested for loops statements to draw hallow boxes of "*"s. The boxes have the same number of rows and columns and this number should be input from the user (valid range: 5 to 21). I'm having trouble coming up with a way to make the box hollow. this is what i have for the code and it comes as a complete square, but i need it to be hollow or just the border.
System.out.println("How many rows/columns(5-21)?");
rows=input.nextInt();
while(rows<5||rows>21){
System.out.println("Out of range. Reenter: ");
rows=input.nextInt();
}
for(m=1;m<=rows;m++){
for(c=1;c<=rows;c++){
System.out.print("*");
}
System.out.println();
}
the output should look like this:
How many rows/columns (5-21)? 25
Out of range. Reenter: 7
*******
* *
* *
* *
* *
* *
*******
解决方案 You need to print only some of the *
s, so add a test before the print("*")
. One option would be to explicitly test the four conditions (top, bottom, left, right) and OR them together logically:
if( (m==1) || //top
(m==rows) || //bottom
(c==1) || //left
(c==rows) //right
) {
System.out.print("*");
} else {
System.out.print(" ");
}
Each m==
test or c==
test identifies one piece of the square. Since the four tests
are ORed together, the if() is true (and a * is printed) if any one of the four tests is true. If none of them are true, the else
runs and prints a space.
I also recommend renaming m
to rowIndex
and c
to colIndex
or something. When you come back to the code a week or two later, more descriptive names will make it easier to pick up where you left off. (Ask me how I know!)
这篇关于如何使用两个for循环做空心的盒子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文