2013-08-25 58 views
0

我有一個問題,以創建一個菱形,我的代碼在這裏:與循環問題決策菱形

package random; 

public class asd { 

    public static void main(String args[]) { 
     for (int j = 1; j <= 4; j++) { 
      for (int kong = 4 - j; kong >= 1; kong--) { 
       System.out.print(" "); 
      } 
      for (int xing = 1; xing <= 2 * j - 1; xing++) { 
       System.out.print("*"); 
      } 
      System.out.println(); 
     } 
     for (int a = 1; a <= 3; a++) { 
      for (int b = 1; b <= a; b++) { 
       System.out.print(" "); 
      } 
      for (int c = 5; c >= 1; c -= 2) { // <==== here 
       System.out.print("*"); 

      } 
      System.out.println(); 
     } 
    } 
} 

但是,輸出是:

 
    * 
    *** 
***** 
******* 
*** 
    *** 
    *** 

我認爲這個問題是在代碼我強調一下,請大家看看,歡呼聲

+0

http://stackoverflow.com/questions/14047583/printing-s-as-triangles-in-java可能有助於 – 2013-08-25 15:36:08

回答

0

你說得對,可能是有問題的一行。感到驚訝的是,你在上半場做得很對:

for (int c = 5; c >= 2*a - 1; c -= 1) { // <==== here 
     System.out.print("*"); 
+0

感謝隊友,非常讚賞 –

0

使用Math.abs將使它更容易。

import java.util.Scanner; 

public class MakeDiamond { 
public static void main(String[] args) { 

Scanner sc = new Scanner(System.in); 

while (true) { 

    System.out.println("Let's Creat Diamonds"); 
    System.out.println("If number increases Diamonds gets bigger. Please input number lager than 1 : "); 

    int user_input = sc.nextInt(); //gets user's input 
    System.out.println(""); 

    int x = user_input; 
    int front_space = -5; 

    for (int i = 0; i < 2 * user_input + 1; i++) { 
     for (int a = front_space; a < Math.abs(i - user_input); a++) { 
      System.out.print(" ");    } 

     if (i < user_input + 1) { 
      for (int b = 0; b < 2 * i + 1; b++) { 
       System.out.print("* "); 
      } 

     } else if (i > user_input) { 
      for (int c = 0; c < 2 * x - 1; c++) { 
       System.out.print("* "); 
      } 
      x--; 
     } 
     System.out.print('\n'); 
    } 

    System.out.println("\nRun Again? 1 = Run, 2 = Exit : "); 

    int restart = sc.nextInt(); 
    System.out.println(""); 

    if (restart == 2) { 
     System.out.println("Exit the Program."); 
     System.exit(0); 
     sc.close(); 
     } 
    } 
    } 
}