2013-07-12 189 views
0

這是我的代碼如何使用嵌套for循環?

public static void main (String[] args) 
{ 
    Scanner keyboard = new Scanner (System.in); 

    int tri, a; 
    int b; 

    System.out.println("Enter the size you want your triangle to be:"); 

    tri = keyboard.nextInt();  

    for (a = 1; a <= tri; a++) 
    { 
     for (b = 1; b <= a; b++) 
     { 
      System.out.print("*"); 
     } 

    } 
} 

當我運行,並進入前。 3我想要的代碼說

enter image description here

我知道我可能會丟失一些圈,因爲我只在代碼的開始階段。我正在奔跑,看看是否所有事情都按照我的意願去做,事實並非如此。當我進入3我在一行中得到的一切:

******

幫助解釋,將不勝感激。

system.out.println(); 

這使得*的是不同的路線,也驗證碼:
應該與任意數量的不只是3

+1

這是之前問。這可以通過遞歸方法來完成。 –

+0

你需要通過''System.out.println();'在代碼中的某處告訴計算機何時應該到達下一行。 –

+0

@huseyintugrulbuyukisik確定它*可以*。然而,問題是關於嵌套for循環。 –

回答

0

這需要每一個外循環被訪問的時間內完成工作只做三角形的上半部分。爲了做下半場,你必須從三分鐘開始倒數。

2

您需要對代碼進行兩處更改。首先,您需要在外部循環的每次迭代中結束該行。其次,你需要做三角形的底部。這裏的代碼,不會它既:

public static void main (String[] args) 
{ 
    Scanner keyboard = new Scanner (System.in); 

    int tri, a; 
    int b; 

    System.out.println("Enter the size you want your triangle to be:"); 

    tri = keyboard.nextInt();  

    for (a = 1; a <= tri; a++) 
    { 
     for (b = 1; b <= a; b++) 
     { 
      System.out.print("*"); 
     } 
     // this next call ends the current line 
     System.out.println(); 
    } 
    // now for the bottom of the triangle: 
    for (a = tri - 1; a >= 1; a--) { 
     for (b = 1; b <= a; b++) 
     { 
      System.out.print("*"); 
     } 
     System.out.println(); 
    } 
} 
+0

這給OP的問題提供了整個解決方案,所以確實是一個解決方案。我雖然這是一個練習,OP使用'System.out.print'和'System.out.println'有問題,然後讓OP繼續處理這個新的方法。 –

+0

謝謝,但究竟是什麼做System.out.println(); 我的意思是該程序如何知道在第一行放置1 *,在第二行放置2 *等等。我只是很難理解和理解這個背後的思想過程。 – xpression

+0

@xpression - 它開始一個新行。 (把它看作是打印一個空白行,除了以前調用'System.out.print()'的時候可能已經有東西了。) –

0

System.out.print打印一切都在電流輸出緩衝區即控制檯。您必須使用System.out.println(請注意ln後綴)打印某些內容和中斷線。

1

或者只是一個循環:

int x = 3; // input tri 
var y = x*2; 

for (int i = 0; i < y; ++i) { 
    for (int j = 0; j < (i < x ? i : y-i); ++j) { 
     System.out.print("*"); 
    } 
    System.out.println(); 
}