You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java二维数组中如何让布尔值'true'在循环后保持不变

公交订票系统座位重置问题修复方案

问题根源

你代码里的核心问题是while循环最开头的嵌套for循环:

for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 3; j++) {
        seatingChart[i][j] = false;
    }
}

这段代码会在用户每次选择继续操作、进入下一轮循环时,强制把所有座位状态重置为false(未预订),导致之前的预订记录全部丢失。而且Java中布尔数组创建时默认所有元素就是false,这段手动初始化完全多余,反而破坏了状态保存逻辑。

修复代码

直接删除这段重置数组的代码即可,修改后的完整代码如下:

import java.util.Scanner;

public class IndividualAssignment {

    public static void main(String[] args) {
        int row, col, seatNumber;
        boolean seatingChart[][] = new boolean[10][3];
        String yesno;
        Scanner input = new Scanner(System.in);
        
        while (true) {
            // Print the seating chart
            for (int i = 0; i < 10; i++) {
                for (int j = 0; j < 3; j++) {
                    if (seatingChart[i][j]) {
                        System.out.print("X ");
                    } else {
                        System.out.print((i * 3 + j + 1) + "  ");
                    }
                }
                System.out.println();
            }
            // Prompt the user to enter a seat number
            System.out.print("Enter a seat number: ");
            seatNumber = input.nextInt();
    
            // Calculate the row and column of the seat based on the seat number
            row = (seatNumber - 1) / 3;
            col = (seatNumber - 1) % 3;
    
            // Check if the seat is available
            if (!seatingChart[row][col]) {
                // If the seat is available, mark it as taken (true)
                seatingChart[row][col] = true;
                System.out.println("Seat " + seatNumber + "(row " + (row + 1) + ", column " + (col + 1) + ") has been reserved.");
            } else {
                // If the seat is not available, print an error message
                System.out.println("Sorry, that seat is already taken.");
            }
            // Print the seating chart
            for (int i = 0; i < 10; i++) {
                for (int j = 0; j < 3; j++) {
                    if (seatingChart[i][j]) {
                        System.out.print("X ");
                    } else {
                        System.out.print((i * 3 + j + 1) + "  ");
                    }
                }
                System.out.println();
            }
    
            System.out.println("Do you want to continue? (y/n)");
            yesno = input.next();
    
            if (yesno.equalsIgnoreCase("n")) {
                break;
            } else if (!yesno.equalsIgnoreCase("y")) {
                System.out.println("Invalid input. Please enter y or n.");
            }
        }
    }
}

修复效果

修改后,用户每次选择继续操作时,之前标记为已预订的座位会保持true状态,座位图表里的X不会消失,新的预订会叠加在已有状态上,完全符合你期望的逻辑。

内容的提问来源于stack exchange,提问作者husinyusoff

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 22:10:11