我正在編寫一個程序,該程序應該像檢票機一樣工作。它會顯示可能的座位選擇圖表及其價格,並詢問用戶是否希望按座位數量或價格選擇座位。它的工作原理就像假設在座位上按數字排序,但是當我嘗試按價格查找座位時,我得到的數組索引超出了界限錯誤。我很困惑,因爲它假設在零點開始線性搜索。我不明白爲什麼會出現這個錯誤。線性搜索期間二維數組中的數組索引超出範圍錯誤
import java.util.Scanner;
public class FindTicket{
public static void main(String[] args){
String answer="number";
Scanner kb=new Scanner(System.in);
int[][] seats= {
{10,10,10,10,10,10,10,10,10,10},
{10,10,10,10,10,10,10,10,10,10},
{10,10,10,10,10,10,10,10,10,10},
{10,10,20,20,20,20,20,20,10,10},
{10,10,20,20,20,20,20,20,10,10},
{10,10,20,20,20,20,20,20,10,10},
{20,20,30,40,40,40,30,30,20,20},
{20,30,30,40,50,50,40,30,30,20},
{30,40,50,50,50,50,50,50,40,30}
};
printChart(seats);
do{
System.out.println("Would you like to choose a seat by number, price, or quit?");
answer = kb.nextLine();
if(answer.equals("price")){
sellSeatbyPrice(seats);}
if(answer.equals("number")){
sellSeatbyNumber(seats);}
printChart(seats);
}while(!answer.equals("quit"));
}
public static void printChart(int[][] seats){
for (int i=0; i<seats.length; i++)
{
for(int j=0; j<seats[0].length; j++)
{
System.out.printf("%8d", seats[i][j]);
}
System.out.println();
}
}
public static int[][] sellSeatbyPrice(int[][] seats){
Scanner kb=new Scanner(System.in);
int ticketprice;
int row = 0, col = 0;
boolean found = false, seatavaliable=true;
do{
System.out.println("What is your prefered ticket price?");
ticketprice=kb.nextInt();
while (row<seats.length && !found){
do{
if(seats[row][col] == ticketprice){
found = true;}
else{
col++; }
}while(col<seats[0].length &&!found);
if(seats[row][col] == ticketprice){
found = true;}
else{
row++;}
}
if(found){
seats[row][col] = 0; }
else {
System.out.println("Seat not found at specified price.");
seatavaliable=false;}
}while(seatavaliable==false);
return seats;
}
public static int[][] sellSeatbyNumber(int[][] seats){
Scanner kb=new Scanner(System.in);
int row = 0, col = 0;
int editedrow, editedcol;
boolean seatavaliable = true;
do{
System.out.println("What is your prefered seat number? Please enter row then column.");
row=kb.nextInt();
col=kb.nextInt();
editedrow = 9-row;
editedcol = col - 1;
if(seats[editedrow][editedcol] > 0){
seats[editedrow][editedcol] = 0;}
else{
System.out.println("Seat is not avaliable.");
seatavaliable=false;}
}while(seatavaliable==false);
return seats;
}
}
你在哪一行得到越界錯誤? – Michael 2013-03-15 01:36:52
要求人們發現代碼中的錯誤並不是特別有效。您應該使用調試器(或者添加打印語句)來分析問題,追蹤程序的進度,並將其與預期發生的情況進行比較。只要兩者發生分歧,那麼你就發現了你的問題。 (然後如果有必要,你應該構造一個[最小測試用例](http://sscce.org)。) – 2013-03-15 01:37:48
@Michael它說我在27和61上有一個錯誤。 – SMoore 2013-03-15 01:44:35