这是我的代码:
import java.util.Scanner;
public class AirlineReservation {
public static void main(String[]args) {
System.out.println("Enter n:");
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[][] airplane = new int[n][4];
for(int i = 1; i < 4; i++) {
System.out.printf("%3d\t", i);
}
for(int j = 0; j <= n; j++) {
System.out.println((j) + " -" + " -" + " -" + " -");
}
}
}
我想要的是在顶部显示四个数字(确实如此),让用户输入一些数字并将其作为行数(确实如此),并为每个打开的部分添加“-”。
我不知道如何做到这一点,并且我在第一行有一些我不想要的 j int 。有人可以帮我解决这个问题吗?
这是输出:
Enter n:
5
1 2 3 4
1 - - - -
2 - - - -
3 - - - -
4 - - - -
5 - - - -
最佳答案
您的代码中有几个错误。
第一个 for 循环应该从 1 开始,到 4 结束(两者都包含),所以我添加了一个 =。
for (int i = 1; i <= 4; i++) {
System.out.printf("%3d\t", i);
}
第二个循环应从 0(包括)开始,到 n(不包括)结束,或者从 1 到 n(都包括)结束。 所以我将其更改为以下内容。此外,您还必须展示每排的所有座位 (4)。所以这个新代码:
for (int row = 1; row <= n; row++) {
System.out.print(j); // Print the number of row
for (int seat = 1; seat <= 4; seat++) {
System.out.print(" -"); // Print each seat
}
System.out.println(""); // Go to the next line
}
但这只会打印空平面。 最好应该打印当前的飞机配置(- 表示空座位,x 表示非空座位)。可以使用以下代码,假设飞机[行][座位]为 0(表示空闲座位)和不同的值(表示已占用座位):
for (int row = 1; row <= n; row++) {
System.out.print(j); // Print the number of row
for (int seat = 1; seat <= 4; seat++) {
System.out.print(" "); // Print separator
if (airplane[row - 1][seat - 1] == 0) {
System.out.print("-");
} else {
System.out.print("X");
}
}
System.out.println(""); // Go to the next line
}
关于java - 如何显示飞机座位表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29652015/