Java票房应用开发:Gross列对齐问题求助
修复票房Top10列表的Gross列对齐问题
你的问题出在Gross列的格式设置上:当前用的%38s字段宽度过大,且字符串默认左对齐,导致票房数值无法整齐对齐。只需调整Gross列的格式符,让它右对齐并设置合适的字段宽度,同时保留Rank和Title列的格式即可解决。
修改后的代码
System.out.printf("%40s%n", "TOP WEEKEND BOX OFFICE"); // 居中标题,布局更可控 System.out.printf("%-10s%-20s%15s%n", "Rank", "Title", "Gross"); // 可选分割线,增强表头与数据的区分度 System.out.printf("%-10s%-20s%15s%n", "-----", "--------------------", "-----------"); System.out.printf("%-10s%-20s%15s%n", "1", "No Good Dead", "24.2 M"); System.out.printf("%-10s%-20s%15s%n", "2", "Dolphin Tale 2", "15.9 M"); System.out.printf("%-10s%-20s%15s%n", "3", "Guardians Of The Galaxy", "8.1 M"); System.out.printf("%-10s%-20s%15s%n", "4", "Teenage Mutant Ninja Turtles", "4.9 M"); System.out.printf("%-10s%-20s%15s%n", "5", "Let's Be Cops", "4.3 M"); System.out.printf("%-10s%-20s%15s%n", "6", "The Drops", "4.1 M"); System.out.printf("%-10s%-20s%15s%n", "7", "If I Stay", "3.9 M"); System.out.printf("%-10s%-20s%15s%n", "8", "The November Man", "2.8 M"); System.out.printf("%-10s%-20s%15s%n", "9", "The Giver", "2.6 M"); System.out.printf("%-10s%-20s%15s%n", "10", "The Hundred-Foot Journey", "2.4 M");
关键修改说明
%15s:将Gross列的格式从%38s改为%15s,去掉负号表示右对齐,15个字符的宽度足够容纳所有票房字符串,同时让所有数值的小数点和单位M整齐对齐,视觉上更规范。- 标题用
%40s居中输出,替代原来的硬编码空格,避免因终端宽度变化导致的布局混乱。 - 新增分割线,让表头与数据的层级更清晰(可按需删除)。
输出效果示例
TOP WEEKEND BOX OFFICE Rank Title Gross ----- -------------------- ----------- 1 No Good Dead 24.2 M 2 Dolphin Tale 2 15.9 M 3 Guardians Of The Galaxy 8.1 M 4 Teenage Mutant Ninja Turtles 4.9 M 5 Let's Be Cops 4.3 M 6 The Drops 4.1 M 7 If I Stay 3.9 M 8 The November Man 2.8 M 9 The Giver 2.6 M 10 The Hundred-Foot Journey 2.4 M
内容的提问来源于stack exchange,提问作者Jayanth V
相关产品推荐
相关产品推荐

