java - 简易巴士预约席
问题描述
给我的任务是确定用户的输入,每当用户输入输入以保留座位时,来自用户的某些输入存储的字符串将替换为“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]);
}
}
}
}
解决方案
为了实现“根据用户输入将存储的字符串“*”替换为“X”。您不需要初始化第二个二维数组(test1)。您可以做的是当您在变量 row1 和 col1 中从用户那里获得输入时。只需使用它们在同一个数组中用 X 替换 * (在你的情况下是“表”)。
int row1 = reader.nextInt();
int col1 = reader.nextInt();
之后,您需要更新名为 table 的二维数组:
table[row1][col1] = "X";
然后可以调用 print 函数打印出更新后的数组。这样,您将只有一个 2D 数组,并且会根据给定的用户输入进行更新。
推荐阅读
- tensorflow - 如何使用 tf.concat() 函数?
- if-statement - 使用 2 个条件输出,第二个条件将使用 2 个不同公式之一
- javascript - 删除由 v-if 条件生成的评论标记
- c# - How to add a user to app in portal.azure's enterprise applications?
- sql - 正则表达式用单个不工作替换多个模式
- php - 如何使用 Htaccess PHP 中的 Mod 重写规则解决 Urls 中类似的参数组合数量
- sql-server - 将tomcat应用程序从redhat连接到sql server时出错
- php - 在不记录 IP 的情况下停止滥用投票系统?
- prometheus - Prometheus 可以将其数据发送到外部 URL 吗?
- ios - 无法完全删除 Fabric 和 Crashlytics