2012-07-10 70 views
0

下面這段代碼給了我一個很長的魚線:簡單的Java魚

<#>< <#>< <#>< <#>< <#>< <#>< <#>< <#>< <#>< <#>< <#>< <#>< (....up to 43 fish) 


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

for (int j=0; j<10; j++) 
{ 
    if ((i*10+j) < 43) 
    { 
    System.out.print(" <#><"); 
    } 

    else{ 
    System.out.print("  "); 

    } 

我試圖找出如何魚限制爲10×10場所以它看起來更像是這樣的:

<#>< <#>< <#>< <#>< <#>< <#>< <#>< <#>< <#>< <#>< 
<#>< <#>< <#>< <#>< <#>< <#>< <#>< <#>< <#>< <#>< 
<#>< <#>< <#>< <#>< <#>< <#>< <#>< <#>< <#>< <#>< 
<#>< <#>< <#>< <#>< <#>< <#>< <#>< <#>< <#>< <#>< 
<#>< <#>< <#>< <#>< 

回答

3
for (int i=0; i<43; i++) 
{ 
    if (i > 0 && i%10 == 0) 
     System.out.println(); 
    System.out.print(" <#><"); 
} 

i % 10是一個模操作。它將i10分開,並返回該部門的其餘部分。示例:如果i17,則結果將是7,因爲17/10 = 1其餘爲7。其餘的是0只發生如果i0,10,20,30,40

i > 0是額外的檢查,以防止你的循環的開始打印一個額外的行權當i仍然00/10 = rest 0

(你可以把多個條件與&&如果所有他們共同擁有要true
你可以把多個條件與||如果他們中的一個true在一起。)

+0

謝謝,我不知道什麼(i> 0 && i%10 == 0)完全正確,但它的工作原理! – 2012-07-10 05:42:58

+1

請參閱我的編輯的解釋。 – 2012-07-10 06:16:10

1

在外部循環的末尾添加一個System.out.println();

1

你缺少的是System.out.println。 println是指打印行。在打印光標移動到下一行之後。

for (int i=0; i<10; i++) { 
     for (int j=0; j<10; j++) { 
      if ((i*10+j) < 43) { 
      System.out.print(" <#><"); 
      } 
      else { 
      System.out.println("  "); 
      } 
     } 
    } 
1

嘗試此....

public class hi { 

    public static void main(String[] args){ 
     int i=0; 
     while (i<43){ 

       for (int j=0 ; j<10 ; j++){ 

       System.out.print(" <#><"); 

       } 
       System.out.println(); 
       i++; 
      } 
    } 
} 
1

在相同的代碼下面的修改將導致與預期輸出。

for (int i=0; i<10; i++) 
{ 
for (int j=0; j<10; j++) 
{ 
    if ((i*10+j) < 43) 
    { 
     System.out.print(" <#><"); 
    } 

    else 
    { 
     System.exit(0);//if fishes exceeds 47 Exit 
    } 
} 
System.out.println();//for new line after 10 fishes 
}