-3

隣り合った座席数を検証するプログラムを作成しました。座席は、0 または 1 で表される、予約済みまたは空席のいずれかです。プログラムは、ほとんどの部分で機能します。連続して必要な数の座席が利用可能な場合、それを示すメッセージが出力されます。必要な数の座席が利用できない場合、または 6 を超える場合に問題が発生します。これを修正するにはどうすればよいですか?

package javaapplication2;
import java.util.*;

public class JavaApplication2 {


    public static void main(String[] args) {
       Scanner input = new Scanner(System.in);
       System.out.println("Enter the amount of people in your group, up to 6");
       int num = input.nextInt();

       int highest = num - 1;

         String available = "";
         String booking = " ";       

       int[] RowA = {0,0,1,0,0,0,1,0,0,1};

        for (int i = 0; i < RowA.length; i++) {
             if (RowA[i] == 0) {
                 available = available + (i + 1);

             }

             if (available.length() > booking.length()) {
                 booking = available;

             }else if (RowA[i] == 1) {
                 available = "";

             }
         }

         char low = booking.charAt(0);
         char high = booking.charAt(highest);


        if (num <= booking.length()) {
            System.out.println("There are seats from " + low + " - " + high + ".");
            System.out.println(booking);
        }
        else {
            System.out.println("Sorry, the desired seat amount is not available. The maximum amount on Row is " + booking.length());

        }
    }
}
4

1 に答える 1

1

まず、質問にスタックトレースを追加してください。
2 つ目 - スタック トレースを読む: コードの何が問題なのかの手がかりが得られます。
3番目 - デバッガーはあなたの親友です:)

実際の例外は次のとおりです。

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
    at java.lang.String.charAt(String.java:686)
    at JavaApplication2.main(JavaApplication2.java:35)

35 行目:char high = booking.charAt(highest);

bookingしたがって、問題は、文字列が必要よりも小さい場合でも、高を計​​算しようとしていることです。ステートメント内の計算highを移動する必要があります。このようにして、必要以上に短くないことを確認できます。lowifbooking

if (num <= booking.length()) {
    char low = booking.charAt(0);
    char high = booking.charAt(highest);
    System.out.println("There are seats from " + low + " - " + high + ".");
    System.out.println(booking);
} else {
    System.out.println("Sorry, the desired seat amount is not available. The maximum amount on Row is " + booking.length());
}
于 2013-02-03T18:56:41.670 に答える