数组不起作用阅读无法解释太多太解释



编写一个程序来验证一排相邻座位的数量。座位已预订或可用,用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());
        }
    }
}

首先,将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字符串比您需要的小,您也要尝试计算高。您应该将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());
}

相关内容

  • 没有找到相关文章