-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

首先 - 将堆栈跟踪添加到您的问题中。
第二 - 阅读堆栈跟踪:它为您提供有关您的代码有什么问题的线索。
第三 - 调试器是你最好的朋友 :)

实际的例外是:

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字符串比你需要的小,你也试图计算高。你应该移动计算highlow内部if语句。这样你就可以确定它booking不比你需要的短:

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 回答