首页 > 解决方案 > 简易巴士预约席

问题描述

给我的任务是确定用户的输入,每当用户输入输入以保留座位时,来自用户的某些输入存储的字符串将替换为“X”,即“X”表示座位已保留. 我应该使用二维数组。

在此处输入图像描述

在此处输入图像描述

我不知道如何根据用户输入将存储的字符串“*”替换为“X”。

到目前为止,这是我的代码。

import java.util.Scanner;

public class ReservationSeat {
    
    public static void main(String []args){
        Scanner reader = new Scanner(System.in);
        
        String[] columns = { "Col 1",  "Col 2",  "Col 3",  "Col 4" };
        for(int i = 0; i < columns.length; i++){
            System.out.print("\t" + columns[i]);

        }
        String[] Rows = { "Row 1 ", "Row 2 ", "Row 3 ", "Row 4 ", "Row 5 ", "Row 6 ", "Row 7 ", "Row 8 ", "Row 9 ", "Row 10 "};
        String [][] table = {
                {"|*", "*","*", "*"},
                {"|*", "*","*", "*"},
                {"|*", "*","*", "*"},   
                {"|*", "*","*", "*"},
                {"|*", "*","*", "*"},
                {"|*", "*","*", "*"},
                {"|*", "*","*", "*"},
                {"|*", "*","*", "*"},
                {"|*", "*","*", "*"},
                {"|*", "*","*", "*"}

        };
        System.out.println();   
        
        for(int row = 0; row < table.length; row++){
            System.out.print(Rows[row]);
            for(int col = 0; col < table[row].length; col++){
                
                System.out.print("\t" + table[row][col]);

            }

            System.out.println();
        }
        
        System.out.print("Enter row and column number to reserve separated by space (Enter a negative number to exit): ");
        int row1 = reader.nextInt();
        int col1 = reader.nextInt();
        table[row1][col1] = reader.next();
        int[][] test1 = new int[row1][col1];
        
        for (int row = 0; row < table.length; row++) {
            System.out.print(Rows[row]);
            
            for(int col = 1; col < test1[row].length; col++) {
                System.out.print("\t" + test1[row1][col1]);
            }
        }
    }
}

标签: javaarrays

解决方案


为了实现“根据用户输入将存储的字符串“*”替换为“X”。您不需要初始化第二个二维数组(test1)。您可以做的是当您在变量 row1 和 col1 中从用户那里获得输入时。只需使用它们在同一个数组中用 X 替换 * (在你的情况下是“表”)。

 int row1 = reader.nextInt();
 int col1 = reader.nextInt();

之后,您需要更新名为 table 的二维数组:

 table[row1][col1] = "X";

然后可以调用 print 函数打印出更新后的数组。这样,您将只有一个 2D 数组,并且会根据给定的用户输入进行更新。


推荐阅读