所以我的任务是创建一个基本上需要看起来像这样的空心方块。
*----*
| |
| |
| |
*----*
(尺寸因用户输入而异) 用户应该输入宽度和长度。至于现在,我已经能够创建一个空心方块和一个完整的正方形和一切。现在,我真的很难过如何用不同的角色创造广场......
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();
}
这就是我走了多远......我在编程的初学者课程中已经有3个星期了,而且在这项任务中我只是输了..
bredde = width和lengde = length btw
答案 0 :(得分:2)
想一想:你是逐行打印的。
第一行和最后一行不同于&#34;中间&#34;它们的形式为 --- ,而另一种形式为| |
所以我们必须区分这两种情况:
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(" ");
}
}
}
}
你能猜出&#34; isFirstOrLastColumn&#34;的代码吗?自己动手?
答案 1 :(得分:0)
这是解决问题的一个非常好的解决方案:
<强>代码强>:
import java.util.Arrays;
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
// query parameters
Scanner in = new Scanner(System.in);
System.out.print("width=");
int width = in.nextInt();
System.out.print("height=");
int height = in.nextInt();
// setup model
char[] headline = new char[width];
Arrays.fill(headline, '-');
headline[0] = '*';
headline[width - 1] = '*';
char[] midline = new char[width];
Arrays.fill(midline, ' ');
midline[0] = '|';
midline[width - 1] = '|';
// draw model
System.out.println(headline);
if (height >= 2) {
for (int r = 1; r < height - 1; r++) {
System.out.println(midline);
}
System.out.println(headline);
}
}
}
假设 width
和height
大于0,可以随意添加代码来处理错误的用户输入。