Java 打印出一个盒子
我想试着打印出一个如下所示的框:Java 打印出一个盒子,java,Java,我想试着打印出一个如下所示的框: +---+---+ | | + + | | +---+---+ 但我不确定如何打印右侧 for (int j = 0; j < x; j++) { System.out.print("+---"); } for (int i = 0; i < y; i++) { for (int j = 0; j < x; j++) {
+---+---+
| |
+ +
| |
+---+---+
但我不确定如何打印右侧
for (int j = 0; j < x; j++) {
System.out.print("+---");
}
for (int i = 0; i < y; i++) {
for (int j = 0; j < x; j++) {
if (j == 0) {
System.out.println("+ +");
System.out.println("| |");
}
}
}
for (int j = 0; j < x; j++) {
System.out.print("+---");
}
for(int j=0;j
x表示长方体的宽度,y表示高度
如果我有一个预设的宽度,这将给我正确的输出,但我想编辑该框,以便可以更改宽度。绘制几个示例。确定哪些部分是通用的,哪些部分是重复的。重复部分是最有趣的,因为它们将成为代码中的循环。在本例中,您将同时拥有垂直和水平重复部分。垂直部分将在外循环中(因为您必须从上到下打印),而水平重复部分将是内循环的一部分(从左到右打印)。有了几个例子后,用不同颜色的铅笔或钢笔在重复出现的地方画线。循环的一次迭代(内部或外部)负责在重复部分的一个实例中打印/写入所有字符。极有可能您的部分(水平和垂直)不是重复的一部分。这些需要在适当的循环之前或之后完成。
公共类Square{
// init to whatever you want
int x = 3; // width
int y = 5; // height
// prepare the lines
// beginning
String width = "+";
String plus = "+";
String pipe = "|";
// build the repeating unit of
// of the line that comes at the top/bottom
for (int i=0; i<x-1; i++) {
width += "-";
}
String tmp = width;
for (int i=0; i<x; i++) {
for (int j = 0; j < x+1; j++) {
plus += " ";
pipe += " ";
}
width += tmp;
}
// add the "closing" char at the end of the line
width += "+";
plus += "+";
pipe += "|";
// draw top
System.out.println(width);
// draw middle
for (int i = 0; i < y; i++) {
if (i % 2 == 1)
System.out.println(plus);
else
System.out.println(pipe);
}
// draw bottom
System.out.println(width);
内部高度内线=5;
无效打印行(int x){
如果(x==1 | | x==heightInLines){
对于(int i=1;i),你应该用一行一行地打印行|
。当你打印左侧时,你还需要打印右侧。除非你使用转义序列移动光标^^“x代表方框的宽度,y代表宽度。”-你可能是说“y代表高度”对吗?@biziclop这太可悲了,他们太酷了!而且很有趣,看手表?v=pX4tBIwhOqY xD
+--+--+--+--+
| |
+ +
| |
+ +
| |
+--+--+--+--+
public class Square {
int heightInLines = 5;
void printLine(int x){
if(x == 1 || x == heightInLines){
for(int i = 1; i <= 9; i ++){
if(i == 1 || i == 5 || i == 9) System.out.print("+");
else System.out.print("-");
}
System.out.println();
}else if(x % 2 == 0) System.out.println("| |");
else System.out.println("+ +");
}
void print(){
for(int i = 1; i <= heightInLines; i++)
printLine(i);
}
public static void main(String[] args) {
new Square().print();
}
}