2016-06-10 59 views
1

所以我應該製作一個程序,用星號創建一個盒子,到目前爲止它不能正確顯示,有時列太小,有時太大,但是從來沒有他們需要的地方。有人可以幫忙!我的星號框程序不能正常工作

import java.util.Scanner; 

public class DisplayBox { 

    public static void drawBar(int length){ 
     for (int i = 1; i <= length; i++){ 
      System.out.print("*"); 
     } 

    } 
    public static void drawHeight(int height, int length){ 
     int h = 0; 
     while (h++ < length - 2){ 
      System.out.print("*"); 
      int h1 = 0; 
      while (h1++ < length - 2){ 
       System.out.print(" "); 
      } 
      System.out.println(" *"); 

     } 
    } 

    public static void main(String[] args){ 
     Scanner input = new Scanner(System.in); 
     System.out.print("Please enter the length of the Box: "); 
     int length = input.nextInt(); 
     System.out.println("Please enter the height!: "); 
     int height = input.nextInt(); 
     System.out.println(); 
     drawBar(length); 
     drawHeight(height, length); 
     drawBar(length); 
    } 
} 

回答

0
  • 你不必在一個​​到println結束線條
  • drawHeight

只是一種風格比較評論對hlength而不是height:它可能是更清晰如果你的方法產生一個給定長度的字符串,然後打印方法都在一個地方:

private String repeat(char ch, int len) { 
    char chars = new char[len]; 
    Arrays.fill(chars, ch); 
    return new String(chars); 
} 

println(repeat('*', length)); 
for (int l = 0; l < length - 2; l++) 
    println("*" + repeat(' ', length - 2) + "*"); 
println(repeat('*', length)); 
0
import java.util.Scanner; 

public class DisplayBox { 

    public static void drawBar(int length){ 
     for (int i = 1; i <= length; i++){ 
      System.out.print("* "); 
     } 
     System.out.print("\n"); 
    } 
    public static void drawHeight(int height, int length){ 
     int h = 0; 
     while (h++ < length - 1){ 
      System.out.print("*"); 
      int h1 = 0; 
      while (h1++ < length-1){ 
       System.out.print(" "); 
      } 
      System.out.println("*"); 

     } 
    } 

    public static void main(String[] args){ 
     Scanner input = new Scanner(System.in); 
     System.out.print("Please enter the length of the Box: "); 
     int length = input.nextInt(); 
     System.out.println("Please enter the height!: "); 
     int height = input.nextInt(); 
     System.out.println(); 
     drawBar(length); 
     drawHeight(height, length); 
     drawBar(length); 
    } 
} 

這似乎確定..雖然