数组不起作用,读不了解太多太解释

时间:2013-02-03 18:46:47

标签: java netbeans stack-trace

写了一个程序来验证连续的座位数量。座位是预订的或可用的,由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());

        }
    }
}

1 个答案:

答案 0 :(得分:1)

首先 - 在你的问题中添加stacktrace 第二 - 阅读stacktrace:它可以为您提供有关代码错误的线索 第三 - 调试器是你最好的朋友:)

实际例外是:

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语句中移动lowif的计算。这样您就可以确保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());
}