gpt4 book ai didi

java - 在 Java 中操作二维数组

转载 作者:搜寻专家 更新时间:2023-11-01 03:36:40 24 4
gpt4 key购买 nike

因此,对于家庭作业,我必须编写一个程序,打印出默认情况下用 - 表示的航空公司座位表(,以表明它们是“开放的”并且有资格预订)。随后,应该提示用户选择他们想要购买的座位,并将数组中该特定位置的值更改为 X

这就是我的代码现在的样子 - 它可以很好地打印出表格,但是当我尝试更改位置时它会给我一个错误:

import java.util.*;

public class AirlineSeeting {

public static void main(String[]args) {
int row = 0;
int colum = 0;
System.out.println("Enter n:");
Scanner scanner = new Scanner(System.in);

int n = scanner.nextInt();
String[][] SeetingChart = new String[n][4];

for (int i = 1; i <= 4; i++) {
System.out.printf("\t%d\t", i);
}

System.out.println("");

for (int j = 1; j <= n; j++) {
System.out.printf("%d", j);
for (int k = 1; k <= 4; k++) {
System.out.print("\t-\t");
}
System.out.println("");
}
for( int i = 0 ; i < SeetingChart.length; i++){
System.out.println("What row would you like to sit in");
row = scanner.nextInt();
System.out.println("What colum would you like to sit in");
colum = scanner.nextInt();
if (SeetingChart[row][colum].equals("X")){
System.out.println("Please pick a seat that is avalable");
}
else if (SeetingChart[row][colum].equals("-")){
SeetingChart[row][colum] = "X";
}
for (int j = 1; j <= 4; j++) {
System.out.printf("\t%d", j);
}

System.out.println("");

for (int j = 1; j <= n; j++) {
System.out.printf("%d", j);
for (int k = 1; k <= 4; k++) {
System.out.print("\t-");
}
System.out.println("");
}
}
}
}

这是执行上述代码时得到的输出:

Enter n:
9
1 2 3 4
1 - - - -
2 - - - -
3 - - - -
4 - - - -
5 - - - -
6 - - - -
7 - - - -
8 - - - -
9 - - - -
What row would you like to sit in
2
What colum would you like to sit in
2
Exception in thread "main" java.lang.NullPointerException
at AirlineSeeting.main(AirlineSeeting.java:30)

如有任何帮助,我们将不胜感激!谢谢!

最佳答案

SeetingChart 是一个对象数组,即 String。因此,所有条目都使用 null 进行初始化。您的程序崩溃于

            if (SeetingChart[row][colum].equals("X")){

因为您尝试在 null 上调用方法(即 equals)。这就是为什么你应该改变声明的原因:

            if ("X".equals(SeetingChart[row][colum])){

这可以防止 NullPointerException

关于java - 在 Java 中操作二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29658436/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com