"线程中的异常" main" java.lang.ArrayIndexOutOfBoundsException:1"

时间:2016-04-21 19:29:09

标签: java

我有一个简单的问题,明天我必须完成。代码编译并运行,但后来我得到一个异常错误。 Sorta有点新手java,我感觉这与多维数组有关。

package question12;

import java.security.SecureRandom;
import java.util.Scanner;



public class Question12 
{

Scanner sc = new Scanner(System.in);

String First_Name, Last_Name, ID, Seat_No;
char seatCh;
String[][] passengerList = new String[1][4];

void setFname()
{
    System.out.printf("Passenger First Name: ");
    First_Name = sc.nextLine();
}

void setLname()
{
    System.out.printf("Passenger Last Name:  ");
    Last_Name = sc.nextLine();
}

void setID()
{
    System.out.printf("Passenger ID:         ");
    ID = sc.nextLine();
}

void setSeatNumber ()
{
    String ticket, StringRandNum;
    String alfabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    int seatCharNum, seatIntNum;

    SecureRandom randomN = new SecureRandom();

    seatIntNum = randomN.nextInt(120);
    seatCharNum = randomN.nextInt(7);

    seatCh = alfabet.charAt(seatCharNum);

    Seat_No = "" + seatIntNum;


}

void generateTicket()
{

    for (int i = 0; i < 39; i++)
    {
        if (i == 19)
        {
            System.out.printf("Air KZN");
        } else
            System.out.print('*');
    }

    System.out.println("");

    System.out.printf("*You are seated in seat number: %s%s%n", seatCh, Seat_No);
    System.out.printf("*Passenger name: %s\n", First_Name);
    System.out.printf("*Passenger surname: %s%n", Last_Name);
    System.out.printf("*Passenger ID: %s%n", ID);

    for (int i = 0; i < 39; i++)
    {
        if (i == 19)
        {
            System.out.printf("Air KZN");
        }

        System.out.print('*');
    } 

    System.out.println("");

}

void storeValues()
{
    passengerList[0][0] = First_Name;
    passengerList[0][1] = Last_Name;
    passengerList[0][2] = ID;
    passengerList[0][3] = Seat_No;
}

void printPassengerList()
{
    System.out.printf("Passenger Name   Passenger Surname   Passenger ID    Seat Number\n");

    for (int a = 0; a < 40; a++)
        System.out.print('-');

    for (int c = 0; c < passengerList.length; c++)
        for (int d = 0; d < passengerList[d].length; d++)
        System.out.print(passengerList[d][c]);
}

public static void main(String[] args) 
{

    Question12 q12 = new Question12();

    q12.setFname();
    q12.setLname();
    q12.setID();
    q12.setSeatNumber();
    q12.generateTicket();
    q12.storeValues();
    q12.printPassengerList();

    }

}

1 个答案:

答案 0 :(得分:1)

你有:

for (int c = 0; c < passengerList.length; c++)
    for (int d = 0; d < passengerList[d].length; d++)
        System.out.print(passengerList[d][c]);

由于两个原因,这会给您一个错误:

  • 您的内部循环应该有passengerList[c].length而不是passengerList[d].length

  • 您的打印输出应为passengerList[c][d]而不是passengerList[d][c}

将其更改为:

for (int c = 0; c < passengerList.length; c++)
    for (int d = 0; d < passengerList[c].length; d++)
        System.out.print(passengerList[c][d]);