2013-02-03 86 views
-3

寫了一個程序來驗證連續相鄰的座位數量。座位是預定的或可用的,由0或1表示。該程序大部分適用。如果所需的一排座位可用,它將輸出一條消息說明。什麼是錯誤的是,當所需的席位數量不可用或超過6.我如何解決這個問題?Array does not work read can not explain too too too explain

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

什麼標題的問題! –

+0

根據您的理想座位數量不可用,什麼*錯誤? – Patrick

+0

聽起來像給我作業。 – Damien

回答

1

首先 - 爲您的問題添加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()); 
} 
+0

添加堆棧跟蹤。 – Damien