java - 如何在java中创建一个循环,在每行上打印略有不同的字符串?

标签 java loops

对于我的第一堂计算机科学课,我正在尝试编写一个程序来打印加拿大国旗的 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/

相关文章:

python - 为什么我的变量会在 python 的嵌套 for 循环中被覆盖?

c - Arduino 开发环境 : Print once inside loop

java - Android 自定义 ListView

java - 将 unicode 字符从 native 字符转换为 Java 字符时出现问题

java - JPA 中的 PostgreSQL 函数 string_agg

c - 即使重复次数限制值为 'i',循环也不会终止,有什么原因吗?

r - 快速建立参数组合模型

Idea IntelliJ Community Edition 的 Java 代码覆盖率工具

java - jOOQ 查询条件和强制类型转换器

java - 循环添加 BigInteger java