Wrote a program to validate the amount of seats adjacent in a row. The seats are either booked or available, represented by 0 or 1. The program works for the most part. If the desired amount of seats in a row is available, it will output a message saying it. What is wrong is when the desired amount of seats is unavailable, or over 6. How do i fix this?
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());
}
}
}
First of all – add stacktrace to your question.
Second – read stacktrace: it gives you a clue about what’s wrong with your code.
Third – debugger is your best friend 🙂
Actual exception is:
Line 35:
char high = booking.charAt(highest);So the problem is that you’re trying to calculate high even if
bookingstring is smaller than you need. You should move calculation ofhighandlowinsideifstatement. This way you can be sure thatbookingis not shorter than you need: