2015-09-20 52 views
0

寫入類LoopPractice。此類必須使用循環打印出以下 圖片。在主要方法中編寫代碼。 第一張圖片:使用循環在java中打印圖像/圖案

 
/

\\ 

/// 

\\\\ 

///// 

\\\\\\ 

/////// 

這是我到目前爲止的代碼:

for(int a=1; a<=7; a=a+2){ 
    for(int i=1; i<=a; i++) 
     System.out.print("/"); 
    System.out.println(" "); 
    for(int c=0; c<a; c=c+2) 
     System.out.print("\\\\"); 
    System.out.println(" "); 
} 

但它打印一行8「\」結尾。在這種情況發生之前不應該終止循環?

回答

0

我假設你剛開始學習編程,所以這裏是你的代碼:

public class LoopPractice { 

    public static void main(String[] args) { 
     for(int counter = 0; counter<7; counter++){ 

      for(int times=0;times<=counter;times++){ 

       if(counter%2==0){ 

        System.out.print("/"); 

       }else{ 

        System.out.print("\\"); 

       } 
      } 

      System.out.println();   
     } 
    } 

} 

chenchuk的代碼比較好,雖然我不知道你是否瞭解三元運算符。如果沒有,你可能想要閱讀this

0

試試這個:

for (int j=1 ; j<8 ; j++){ 
    for(int k=0 ; k<j ; k++){ 
     // checking if row number is Even/Odd to print '\' or '/' 
     System.out.print((j%2 == 0)? "\\" : "/"); 
    } 
    System.out.println(); 
}