2014-09-04 50 views
0

所以我開始在Java編程語言的世界中,並且試圖打印X高度的聖誕樹。到目前爲止,它的工作,但如果例如用戶輸入4,它會打印4行+聖誕樹樹樁,至少意味着5.但是,我想它是4包括殘端。到目前爲止我有這樣的:製作更小的聖誕樹

public class xmas { 

    public static void main(String[] args) 
    { 
     Scanner scan = new Scanner(in); 
     out.print("please enter a number: "); 
     int temp = scan.nextInt(); 
     int x = (temp-1)*2 +1; 
     int y = x/2; 
     int z = 1; 
     for(int i=0; i<temp; i++) 
     { 
      for(int j=0; j<=y; j++) 
      { 
       out.print(" "); 
      } 
      for(int k = 0; k<z; k++) 
      { 
       out.print("*"); 
      } 
      out.println(); 
      y--; 
      z+=2; 
     } 
     for(int i =0; i<=x/2; i++) 
     { 
      out.print(" "); 
     } 
     out.println("*"); 
    } 
} 

我不知道該怎麼做。謝謝!

+1

這是很好的,你已經開始了你的準備工作;) – 2014-09-04 21:47:15

+0

是什麼意思呢? – Happycoder21 2014-09-04 21:47:55

+1

這是一個笑話 - 聖誕節是從現在起3個月;)你是如何得到聖誕樹的想法?無論如何 - 你有沒有考慮過在使用'temp - ;'後輸入'int temp = scan.nextInt();'? – 2014-09-04 21:51:24

回答

1

嘗試使用temp--剛輸入後,這樣的:

int temp = scan.nextInt(); 
temp--; 

或降低循環條件:在這兩種情況下

for(int i=0; i<temp-1; i++) 

輸出:

* 
    *** 
    ***** 
    * 
+0

非常感謝! :) – Happycoder21 2014-09-04 22:28:09

+0

@ Happycoder21沒問題 - 很高興我能幫到你。 – 2014-09-04 22:32:36

0

如果你只是從輸入中減去一個,你的聖誕樹應該是正確的大小。下面是它會是什麼樣子(使用Java樣式慣例):

public class ChristmasTree { 
    public static void main(String[] args) { 
     Scanner scanner = new Scanner(in); 
     out.print("Please enter a number: "); 

     int temp = scanner.nextInt() - 1; // note the `- 1` 
     int x = (temp - 1) * 2 + 1; 
     int y = x/2; 
     int z = 1; 

     for(int i = 0; i < temp; i++) { 
      for(int j = 0; j <= y; j++) { 
       out.print(" "); 
      } 

      for(int j = 0; j < z; k++) { 
       out.print("*"); 
      } 

      out.println(); 
      y--; 
      z += 2; 
     } 

     for(int i =0; i<=x/2; i++) { 
      out.print(" "); 
     } 

     out.println("*"); 
    } 
} 
+0

非常感謝! :)這個作品呢! – Happycoder21 2014-09-04 22:26:15