2012-10-23 38 views
-3

我將如何使用三種方法來產生這樣的輸出?畫一個正方形?任何人都可以請解釋

Please enter the fill character: "z" 
Please enter the size of the box (0 to 80): "3" 
+---+ 
|zzz| 
|zzz| 
|zzz| 
+---+ 

我的代碼能夠生成一個盒子,但是我有問題了解使用其他方法來創建它周圍的邊框。

import java.util.Scanner; 
public class SolidBoxes 
{ 
    public static void main(String[] args) 
    { 
     int start = 0; 
     Scanner scan = new Scanner(System.in); 

     System.out.print("Please enter the fill character: "); 
     String character = scan.next(); 

     System.out.print("Please enter the size of the box (0 to 80): "); 
     int size = scan.nextInt(); 

     if (size > 80 || size < 0) 
     { 
      System.out.println("Please enter the size of the box (0 to 80): "); 
      size = scan.nextInt(); 
     } 

     for (int i = 0; i < size; i++) 
     { 

      System.out.println(); 

      for (int j = 0; j < size; j++) 
      { 
      System.out.print(character); 
      } 

     } 
    } 
} 

這使我的輸出:

Please enter the fill character: z 
Please enter the size of the box (0 to 80): 3 

zzz 
zzz 
zzz 

怎麼可能添加其他兩種方法爲「+ - +」和另一種方法「|」?

+7

您從*編碼* ..開始 –

+0

謝謝羅素,是否可以使用三種不同的方法創建一個盒子? – Leroy

+2

[你有什麼嘗試?](http://whathaveyoutried.com/) – ruakh

回答

0

方法提供了一種將部分代碼劃分爲要執行的各種任務的方法。通常,一個方法將執行特定任務所需的所有操作。當調用代碼想要執行您在該方法中實現的特定任務時,將從其他代碼調用方法。例如,如果你想畫在你的主要的形狀,你可能有一個看起來像這樣的方法:只要你想得出這樣的形狀,你只需調用這樣的方法

public void drawShape(...){ 
     ... 
     //Put specific code to draw the shape here 
     ... 
    } 

內。然後你的主:

 drawShape(...); 

在上面的public部件的製備方法是訪問修飾符告訴我們,這種方法是公開的任何代碼,可以「看到」它。 void部分是返回類型,在這種情況下它不返回任何內容。 drawShape是方法名稱。

就你而言,它看起來像你需要提供三種獨立的方法。首先你應該定義一個方法來輸出你的第一行,然後得到填充字符並將它返回給main。然後提供第二種方法輸出第二行並將該框的大小返回給main。最後提供第三種方法根據您收到的前兩個輸入輸出框。當你寫完這三種方法後,按照正確的順序從main調用它們來運行完整的程序。

+0

非常感謝湯姆,這是我尋求的幫助。 – Leroy

相關問題