如何为Java实现的美国国旗控制台程序添加颜色效果
为Java打印美国国旗程序添加颜色效果
你现有一个黑白打印美国国旗的Java程序,现在需要为其添加控制台颜色效果,可通过ANSI转义序列实现(大多数主流终端都支持该特性)。
原黑白版本代码
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package americanflag; /** * * @author abzdino */ public class AmericanFlag { /** * @param args the command line arguments */ public static void main(String[] args) { String p1 = "* * * * * * ==================================\n * * * * * =================================="; String p2 = "=============================================="; for (int i = 0; i < 4; i++) { System.out.println(p1); } System.out.println("* * * * * * =================================="); for (int i = 0; i < 6; i++) { System.out.println(p2); } } }// TODO code application logic here
添加颜色后的代码实现
利用ANSI转义码设置文本颜色、背景色,模拟美国国旗的蓝底白星、红白条纹效果:
package americanflag; public class AmericanFlag { public static void main(String[] args) { // ANSI转义码定义 final String RESET = "\u001B[0m"; // 重置所有格式 final String WHITE_TEXT = "\u001B[37m"; // 白色文本 final String BLUE_BG = "\u001B[44m"; // 蓝色背景 final String RED_BG = "\u001B[41m"; // 红色背景 final String WHITE_BG = "\u001B[47m"; // 白色背景 // 星区部分:蓝底白星 String starLine1 = BLUE_BG + WHITE_TEXT + "* * * * * * " + RESET; String starLine2 = BLUE_BG + WHITE_TEXT + " * * * * * " + RESET; // 条纹部分前缀(星区后接的条纹) String stripeRed = RED_BG + "==============================================" + RESET; String stripeWhite = WHITE_BG + "==============================================" + RESET; // 打印4组双行星区+条纹 for (int i = 0; i < 4; i++) { System.out.println(starLine1 + stripeRed); System.out.println(starLine2 + stripeWhite); } // 打印最后一行星区+条纹 System.out.println(starLine1 + stripeRed); // 打印剩余的条纹(因为前面已经打印了4组红白,还需2条红白) System.out.println(stripeWhite); System.out.println(stripeRed); } }
代码说明
- 用
\u001B[XXm格式的ANSI转义码控制颜色,RESET用于恢复终端默认格式,避免后续输出受影响 - 星区部分设置为蓝色背景+白色文本,模拟国旗的蓝白星区域
- 条纹部分交替使用红色背景和白色背景,还原国旗的红白条纹
- 调整了原代码的拼接逻辑,确保星区和条纹的颜色正确对应
内容的提问来源于stack exchange,提问作者AAMODZ C.P
相关产品推荐
相关产品推荐

