对于我的第一堂计算机科学课,我正在尝试编写一个程序来打印加拿大国旗的 ASCII 设计。我已经有了一个可以运行的程序,但它体积庞大,我希望能够简化它。有没有办法让循环打印相同的输出?
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");
最佳答案
您可以使用数组。并且,在 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);
关于java - 如何在java中创建一个循环,在每行上打印略有不同的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41733512/