2014-07-04 46 views
0

我想嘗試並打印出一個盒子,看起來像:打印了一個盒子

+---+---+ 
|  | 
+  + 
|  | 
+---+---+ 

,但我對如何打印出右側不確定。

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("+---"); 
    } 

x代表框的寬度,y代表高度。


這將給我正確的輸出,如果我有一個預設的寬度,但我想編輯框,所以我可以改變寬度。

+3

你應該打印行''| |'用一個for循環 –

+1

想想它一行一行。當您打印左側時,還需要打印右側。 –

+0

除非使用轉義序列來移動光標^^ – MightyPork

回答

0
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(); 

    } 
} 

請注意,這不是一個通用的解決方案即不能打印任何尺寸的平方。但它打印出你要求的東西,加上它很容易,並且修改代碼以使其打印所有大小的正方形(可以通過在print()方法中或在構造函數中傳遞參數,由你決定:)

0

畫幾個例子。確定哪些部分是共同的,哪些部分重複。重複的部分是最有趣的,因爲它們將成爲代碼中的循環。在你的情況下,你將有垂直和水平重複部分。垂直部分將位於外部循環中(因爲您必須從上到下打印),而水平重複部分將成爲內部循環的一部分(從左向右打印)。一旦你有幾個例子,使用不同的彩色鉛筆或鋼筆繪製標記重複發生的地方。循環的一次迭代(內部或外部)負責在重複部分的一個實例中打印/寫入所有字符。很有可能你會有不屬於重複的部分(水平和垂直)。這些將需要在適當的循環之前或之後完成。

0
// 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); 

打印:

+--+--+--+--+ 
|   | 
+   + 
|   | 
+   + 
|   | 
+--+--+--+--+