【发布时间】:2019-03-25 18:06:51
【问题描述】:
我很难弄清楚为什么当我运行我的代码时,它会跳过所有的 if 语句并且只是将其置为无效。我有一个二维数组,其值代表一个电影院,我应该卖票,用户应该输入一笔钱来确定他们将坐在哪里,这是他们能负担得起的最昂贵的座位选择。该人获得的座位应该从任何数字更改为 0。最后我需要打印带有零的新数组。
这是我尝试过的:
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
boolean done = false;
//initial seating chart
int [] [] table =
{
{10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{20, 20, 20, 20, 20, 20, 20, 20, 20, 20},
{20, 20, 20, 20, 20, 20, 20, 20, 20, 20},
{30, 30, 30, 30, 30, 30, 30, 30, 30, 30},
{40, 40, 40, 40, 40, 40, 40, 40, 40, 40},
{40, 40, 40, 40, 40, 40, 40, 40, 40, 40},
{50, 50, 50, 50, 50, 50, 50, 50, 50, 50},
};
while (!done) {
int row; int col;
//search seating chart
for (row=0; row<9; row++) {
for (col=0; col<8; col++) {
System.out.printf("Enter maximum amount that you would like to spend on the tickets: ");
int amount = in.nextInt();
if (table[row][col]==10 && 10<=amount && amount<20) {
table[row][col]=0;
System.out.printf("Ticket located at Row %d Seat %d purchased for 10\n", row+1, col+1);
System.out.print("Would you like to purchase additional tickets? (Y/N) " + in.next());
if (in.hasNext("y")) {
done = false;
}
else {done = true;
}
}
else if (table[row][col]==20 && 20<=amount && amount<30) {
table[row][col]=0;
System.out.printf("Ticket located at Row %d Seat %d purchased for 20\n", row+1, col+1);
System.out.print("Would you like to purchase additional tickets? (Y/N) " + in.next());
if (in.hasNext("y")) {
done = false;
}
else {done = true;
}
}
else if (table[row][col]==30 && 30<=amount && amount<40) {
table[row][col]=0;
System.out.printf("Ticket located at Row %d Seat %d purchased for 30\n", row+1, col+1);
System.out.print("Would you like to purchase additional tickets? (Y/N) " + in.next());
if (in.hasNext("y")) {
done = false;
}
else {done = true;
}
}
else if (table[row][col]==40 && 40<=amount && amount<50) {
table[row][col]=0;
System.out.printf("Ticket located at Row %d Seat %d purchased for 40\n", row+1, col+1);
System.out.print("Would you like to purchase additional tickets? (Y/N) " + in.next());
if (in.hasNext("y")) {
done = false;
}
else {
done = true;
}
}
else if (table[row][col]==50 && 50<=amount) {
table[row][col]=0;
System.out.printf("Ticket located at Row %d Seat %d purchased for 50\n", row+1, col+1);
System.out.print("Would you like to purchase additional tickets? (Y/N) " + in.next());
if (in.hasNext("y")) {
done = false;
}
else {done = true;
}
}
else {System.out.print("invalid");}
}}}
//final seating chart
System.out.print(table);
}
}
【问题讨论】:
-
JavaScript 和 Java 是两种不同的编程语言。
-
谢谢。尽管如此,你能帮我吗?
-
您不需要循环 2 个 for 循环,客户必须非常幸运才能获得行和列处于他想坐的价格范围内的座位,就像一开始一样如果我选择 45 -> 那么我进入第三个 else if 但此时 table[0][0] 为 10 所以它失败了.. 我正在编写一个代码示例,可以更好地解释
标签: java arrays loops if-statement