[英]Code doesn't work in Java (arrays)
我有一項作業要編寫一個代碼,要求您提供 10 個座位(有些已被占用,有些是空的),您需要獲得一個座位,檢查它是否可用,如果沒有找到最近的空座位。
有時我的代碼有效,但大多數時候無效。 有人能幫我嗎?
import java.util.Scanner;
public class Main {
static Scanner reader = new Scanner(System. in );
public static void main(String[] args) {
int mult = 1;
int[] manage = new int[10];
System.out.println(" 0- empty 1-taken ");
for (int i = 0; i < 10; i++) {
System.out.println("enter the " + (i + 1) + " place");
manage[i] = reader.nextInt();
}
int a = 0, check = 0;
System.out.println("What the place you want to seat in?: ");
a = (reader.nextInt()) + 1;
System.out.println("checking...");
while (check != 5) {
if (manage[a] == 0) {
System.out.println(" your seat is in the " + a + " place");
check = 5;
} else if (manage[a - mult] == 0) {
System.out.println(" your seat is in the " + ((a - mult) + 1) + " place");
check = 5;
} else if (manage[a + mult] == 0) {
System.out.println(" your seat is in the " + ((a + mult) + 1) + " place");
check = 5;
} else {
mult++;
}
}
}
}
我想你想要的這條線是
a = (reader.nextInt()) - 1;
代替
a = (reader.nextInt()) + 1;
由於您始終為所有輸出顯示“實際索引 + 1”,即
用戶處理 1 - 10 而不是 0 - 9 ?
注意:如果值 < 0或值 >= 數組長度, manage[a - mult] 和 manage[a + mult] 可以拋出 ArrayIndexOutOfBoundsException 。
注意#2:在else
子句中,一旦mult
>= 數組長度,您就可以跳出循環。 如果您不添加它,如果所有座位從一開始就被占用,則循環將不斷重復。
因此,在訪問該數組索引之前添加檢查,如下所示:
if (manage[a] == 0) {
System.out.println("Your seat is in the " + a + " place");
check = 5;
} else if ( a - mult >= 0 && manage[a - mult] == 0) {
System.out.println("Your seat is in the " + ((a - mult) + 1)
+ " place");
check = 5;
} else if (a + mult < manage.length && manage[a + mult] == 0) {
System.out.println("Your seat is in the " + ((a + mult) + 1)
+ " place");
check = 5;
} else {
mult++;
// Check is necessary here, infinite loop if all seats are taken!
if(mult >= manage.length) {
System.out.println("All seats taken!");
break;
}
}
輸入/輸出(更改后):
0 - Empty 1 - Taken
Enter the 1 place: 0
Enter the 2 place: 0
Enter the 3 place: 1
Enter the 4 place: 1
Enter the 5 place: 1
Enter the 6 place: 1
Enter the 7 place: 1
Enter the 8 place: 1
Enter the 9 place: 1
Enter the 10 place: 1
What is the place you want to sit in?: 10
checking...
Your seat is in the 2 place
0 - Empty 1 - Taken
Enter the 1 place: 1
Enter the 2 place: 1
Enter the 3 place: 1
Enter the 4 place: 1
Enter the 5 place: 0
Enter the 6 place: 1
Enter the 7 place: 1
Enter the 8 place: 1
Enter the 9 place: 0
Enter the 10 place: 1
What is the place you want to sit in?: 1
checking...
Your seat is in the 5 place
在上面的例子中,用戶輸入 10,但你的程序檢查數組索引 9。
數組索引 9 被占用,所以你檢查數組索引 8 (9-1),它是空的,並告訴用戶座位 #9 是他的座位。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.