所以我的任务是创建一个空心正方形,它基本上需要看起来像这样。
*----*
| |
| |
| |
*----*
(大小根据用户输入而变化) 用户应该输入宽度和长度。就目前而言,我已经能够创建一个空心正方形和一个完整的正方形等等。现在我真的很困惑如何用不同的角色创建正方形..
import java.util.Scanner;
public class HulR{
public static void main (String []args) {
Scanner tastatur = new Scanner(System.in) ;
int bredde;
int lengde;
System.out.print("bredde") ;
bredde = tastatur.nextInt();
System.out.print("lengde");
lengde = tastatur.nextInt();
for (int j = 1; j<= bredde; j++)
for (int i = 1; i <= lengde; i++){
if (i == 1 || i == lengde)
System.out.print("*");
else
System.out.print("|");
System.out.println();
}
这就是我已经走了多远..我已经进入初学者编程类(class)三周了,当谈到这项任务时我只是迷失了..
bredde = 宽度,lengde = 长度(btw)
最佳答案
想一想:您正在逐行打印它。
第一行和最后一行与“中间”行的不同之处在于它们的形式为 --- ,而另一行的形式为 | |.
因此我们必须区分这两种情况:
for (int i = 1; i<=height; i++) {
for (int j = 1; j<=width; j++) {
if (isFirstOrLastLine(i, height)) {
//print like this: *--*
}
else {
//print like this : | |
}
}
}
现在,我们如何知道我们是在第一行还是最后一行:
boolean isFirstOrLastLine(int line, int height) {
return i == 1 || i == height;
}
现在我们可以填写打印实际行的逻辑!
for (int i = 1; i<=height; i++) {
for (int j = 1; j<=width; j++) {
if (isFirstOrLastLine(i, height)) {
//print like this: *--*
if (isFirstOrLastColumn(j, width)) {
System.out.print("*");
}
else {
System.out.print("-");
}
}
else {
//print like this : | |
if (isFirstOrLastColumn(j, width)) {
System.out.print("|");
}
else {
System.out.print(" ");
}
}
}
}
您能自己猜出“isFirstOrLastColumn”函数的代码吗?
关于java - java中不同字符的空心正方形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32459773/