Java如何使用二维数组创建影院座位表并实现左侧行号打印
解决方法
你只需要调整每行座位前的打印内容,将原本输出的两个空格替换为对应行号即可,行号从1开始计数(对应数组遍历的索引i+1),推荐使用格式化输出保证行列对齐。
修改后的完整代码如下:
import java.util.Scanner; public class CinemaSeat { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int row = scanner.nextInt(); int seat = scanner.nextInt(); char[][] array = new char[row][seat]; // 可在此处给array数组赋值自定义座位状态,比如已售改为其他字符,这里保持原有逻辑默认打印S // 打印顶部座位号 System.out.print(" "); for (int i = 1; i < seat + 1; i++) System.out.print(i + " "); System.out.println(); // 打印每行座位,新增行号输出 for (int i = 0; i < array.length; i++) { // 替换原来的两个空格,输出行号,左对齐占2位保证布局对齐 System.out.printf("%-2d", i + 1); for (int j = 0; j < array[i].length; j++) System.out.print('S' + " "); System.out.println(); } scanner.close(); } }
效果示例
输入3 5时,输出效果如下:
1 2 3 4 5 1 S S S S S 2 S S S S S 3 S S S S S
内容的提问来源于stack exchange,提问作者Yang89
相关产品推荐
相关产品推荐

