代码在 Java 中不起作用(数组)



我有一个任务,要写一个代码,要求你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

注意:manage[a - mult] 和 manage[a + mult] 可以抛出 ArrayIndexOutOfBoundsException,如果值<0>值是>= 数组长度

注意 #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 是他的席位。

最新更新