2017-01-19 3 views
0

私の最初のコンピューター科学のクラスでは、カナダの国旗のASCIIデザインを印刷するプログラムを作成しようとしています。私はすでに働いているプログラムを持っていますが、かさばりますし、簡単にすることを望んでいました。同じ出力をループ印刷する方法はありますか?Javaでループを作って、各行にわずかに異なる文字列を出力する方法はありますか?

public class Flag{ 
/* 
    * Uses fixed combinations of ASCII characters to produce 
    * the Canadian flag. 
*/ 
    public static void main(String args[]){ 

    //Components of flag 
    String topAndBottom ="|---------------------------------------|"; 
    String leftSide = "|**********"; 
    String rightSide = "**********|"; 
    String flagRow1 ="     "; 
    String flagRow2 ="  ^  "; 
    String flagRow3 =" ^/*\\^ "; 
    String flagRow4 ="  /*\\|*|/*\\  "; 
    String flagRow5 =" . --*********-- . "; 
    String flagRow6 =" \\*********/ "; 
    String flagRow7 ="  >*******<  "; 
    String flagRow8 =" *********** "; 
    String flagRow9 ="  ---------  "; 
    String flagRow10 ="  | |  "; 

    //Print flag 
    System.out.println(" "+"\n"+ 
    topAndBottom+"\n"+ 
    leftSide+flagRow1+rightSide+"\n"+ 
    leftSide+flagRow2+rightSide+"\n"+ 
    leftSide+flagRow3+rightSide+"\n"+ 
    leftSide+flagRow4+rightSide+"\n"+ 
    leftSide+flagRow5+rightSide+"\n"+ 
    leftSide+flagRow6+rightSide+"\n"+ 
    leftSide+flagRow7+rightSide+"\n"+ 
    leftSide+flagRow8+rightSide+"\n"+ 
    leftSide+flagRow9+rightSide+"\n"+ 
    leftSide+flagRow10+rightSide+"\n"+ 
    leftSide+flagRow1+rightSide+"\n"+ 
    topAndBottom+"\n"); 
+2

ようこそ!コード改善の提案に適した[Code Review subsite](https://codereview.stackexchange.com/)をチェックしたいかもしれません –

答えて

2

あなたは配列を使用することができます。また、Java 8以降では、Streamのように

// Components of flag 
String topAndBottom = "|---------------------------------------|"; 
String leftSide = "|**********"; 
String rightSide = "**********|"; 
String[] rows = { "     ", // 
     "  ^  ", // 
     " ^/*\\^ ", // 
     "  /*\\|*|/*\\  ", // 
     " . --*********-- . ", // 
     " \\*********/ ", // 
     "  >*******<  ", // 
     " *********** ", // 
     "  ---------  ", // 
     "  | |  ", // 
     "     " }; 
System.out.println(topAndBottom); 
Stream.of(rows).forEachOrdered(r -> System.out.println(leftSide + r + rightSide)); 
System.out.println(topAndBottom); 
+0

なぜストリームに気をつけますか?それぞれのループのために何が間違っていますか? –

関連する問題