Java 使用终端的数组索引超出范围

Array Index out of bounds for Java using terminal

我在尝试使用 java 创建的票务系统时遇到问题。我正在尝试利用两个文件来读取和写入我的输入。我目前只使用 salesSell 方法进行测试。我正在使用终端传递参数。我遇到的问题是抛出的 arrayoutofbounds 异常。

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at cisc_327_frontend.Frontend_try1.main(Frontend_try1.java:763)

我传递的两个数组参数是从我当前事件文件中的同一行解析而来的。文件中一行的示例是:"testevent1__________0003"。我似乎无法弄清楚我在哪里遇到这个问题。任何类型的指导将不胜感激。

package cisc_327_frontend;
import java.io.*;
import java.util.*;

public class Frontend_try1 {

private static File fileOutput;
private static List<StringBuilder> eventTrans = new ArrayList<>();


public static void consoleInput(String[] namesArray, int[] ticketArray,File fileCurrentEvents){
    System.out.println("Enter command:");
    Scanner input = new Scanner(System.in);
    String inputString = input.nextLine();


    boolean correct = true;

        do{

            if(inputString.toUpperCase().equals( "LOGIN")) {
                //enter login mode
                login(namesArray, ticketArray,fileCurrentEvents);
                correct = true;

                }
            if(inputString.toUpperCase().equals("LOGOUT")){
                logout(namesArray, ticketArray,fileCurrentEvents);
                correct=true;
            }
                if (!"LOGIN".toUpperCase().equals(inputString) || !"LOGOUT".toUpperCase().equals(inputString)){
                    System.out.println("Incorrect command, please enter command:");
                    input = new Scanner(System.in);
                    inputString = input.nextLine();
                    correct = false;
                }

        }while(!correct);



    }

public static void login(String[] namesArray, int[] ticketArray,File fileCurrentEvents) {
    System.out.println("Sales or Admin?");
    Scanner input = new Scanner(System.in);
    String inputString = input.nextLine();


    boolean correct = true ;

    do {
        if(inputString.toUpperCase().equals("LOGOUT")){
            logout(null, null, null);

        }
        else if(inputString.toUpperCase().equals("SALES")) {
            //enter sales mode
            sales(namesArray, ticketArray,fileCurrentEvents);
            correct = true;
        } else if (inputString.toUpperCase().equals("ADMIN")) {
            //enter admin mode
            admin(namesArray, ticketArray,fileCurrentEvents);
            correct = true;
        } else if (inputString.toUpperCase().equals("LOGOUT")) {
            //enter logout mode
            logout( namesArray, ticketArray, fileCurrentEvents);
            correct = true;
        } else  {
            //ask again
            System.out.println("Invalid Input");
            System.out.println("Sales or Admin?");
            input = new Scanner(System.in);
            inputString = input.nextLine();
            correct = false;
        }

    }while(!correct);

}

public static void sales(String[] namesArray, int[] ticketArray,File fileCurrentEvents) {
    //System.out.println("SALES");
    System.out.println("Sales Mode");
    System.out.println("Enter Command:");
    Scanner input = new Scanner(System.in);
    String inputString = input.nextLine();


    boolean correct = true ;

    do {
        if(inputString.toUpperCase().equals("LOGOUT")){
            logout( namesArray, ticketArray, fileCurrentEvents);

        }
        else if(inputString.toUpperCase().equals("SELL")) {
            //enter sales Sell mode
            salesSell(namesArray, ticketArray,fileCurrentEvents);
            correct = true;
        } else if (inputString.toUpperCase().equals("RETURN")) {
            //enter sales Return mode
            salesReturn(namesArray, ticketArray,fileCurrentEvents);
            correct = true;
        } else if (inputString.toUpperCase().equals("LOGOUT")) {
            //enter Logout mode
            logout( namesArray, ticketArray, fileCurrentEvents);
            correct = true;
        } else {
            //ask again
            System.out.println("Invalid Input");
            System.out.println("Enter Command:");
            input = new Scanner(System.in);
            inputString = input.nextLine();
            correct = false;
        }

    }while(!correct);



}


public static void salesSell(String[] namesArray, int[] ticketArray,File fileCurrentEvents) {
    int index = 0;
    String eventName = null;
    int numberTickets = 0;
    System.out.println("Sales Sell Mode");

    System.out.println("What is the name of your event?");
    Scanner input = new Scanner(System.in);
    String inputString = input.nextLine();

    if(inputString.toUpperCase().equals("LOGOUT")){
        logout( namesArray, ticketArray, fileCurrentEvents);

    }

    try{

        for(int i = 0; i < namesArray.length; i++) {
            if(namesArray[i].equals(inputString)){
                index = i;
            }
        }
         eventName= namesArray[index];
          numberTickets=ticketArray[index] ;

    } catch (Exception e) {
        System.out.println("Error: Event not found within file");
        System.exit(1);
    }

    int event = inputString.length();
    boolean charnumber = true;

    do{
        if(inputString.toUpperCase().equals("LOGOUT")){
            logout( namesArray, ticketArray, fileCurrentEvents);

        }
    if(event< 0 || event >20){

        System.out.println("No more than 20 characters allowed for name!");
        System.out.println("Enter name:");
        input = new Scanner(System.in);
        inputString = input.nextLine();
        event=inputString.length();
        charnumber = false;
    }
    else{
        charnumber = true;

    }

    } while(!charnumber);


    System.out.println("How many tickets?");
    input = new Scanner(System.in);
    inputString = input.nextLine();
    int digit;


    while(true){
    try {
        digit = Integer.parseInt(inputString);

    break;
    }
    catch(NumberFormatException e){


    }


    System.out.println("Please type a number!");    
    inputString = input.nextLine(); 
    }

if( numberTickets - digit <0){
    System.out.println("Illegal amount of tickets! Buy less ticket please.");

}
else{
    int tickets = numberTickets - digit;

    ticketArray[index]=tickets;


}
    boolean dignumber = true;

    do{
        if(inputString.toUpperCase().equals("LOGOUT")){
            logout( namesArray, ticketArray, fileCurrentEvents);

        }
    if(digit<0 || digit>8){

        System.out.println("Only 8 tickets allowed to be sold!");
        inputString = input.nextLine();
        event=inputString.length();

        dignumber = false;
        digit= Integer.parseInt(inputString);
    }
    else{
        dignumber= true;

    }
    }while(!dignumber);

}




public static boolean logout(String[] namesArray, int[] ticketArray,File fileCurrentEvents) {
    FileWriter logoutFileWriter;
    FileWriter currEventsFileWriter;
    int numSpaces = 0;

    try{
        currEventsFileWriter = new FileWriter(fileCurrentEvents, true);

            for(int i = 0; i < namesArray.length; i++ ) {
                currEventsFileWriter.write(namesArray[i]);
                numSpaces = 20 - (namesArray[i].length() + 4);
                for(int j = 0; j < numSpaces; j++) {
                    currEventsFileWriter.write("_");
                }
                currEventsFileWriter.write(ticketArray[i]);
                currEventsFileWriter.write(String.format("%n"));
            }       

    } catch(IOException e) {
        System.out.println("Rewriting Current Events File Error");
        System.exit(1);
    }

    try {
        logoutFileWriter = new FileWriter(fileOutput, true);

        //Cycle through event trans file and write via filewriter
        for(int i = 0; i < eventTrans.size(); i++ ) {
            String transact = eventTrans.get(i).toString();
            logoutFileWriter.write(transact);
            logoutFileWriter.write(String.format("%n"));
        }
        // Signify end of file
        logoutFileWriter.write("00                       000000 00000");
        logoutFileWriter.write(String.format("%n"));
        logoutFileWriter.close();
        fileOutput.createNewFile();

    } catch(IOException e) {
        System.out.println("Output File Error");
        System.exit(1);
    }
    return true;

    /*
    for( int i = 0; i < 20; i++ ) {
        System.out.println("");
    }
    System.out.println("Logged Out");
    consoleInput();
*/
}



public static void main(String[] args){

    try {
        File fileCurrentEvents = new File(args[0]);
        fileOutput = new File(args[1]);

        // Read current events file for events & dates
        FileReader fileRead = new FileReader(fileCurrentEvents);
        BufferedReader buffRead = new BufferedReader(fileRead);

        // Create strings for data in current events file
        String currentLine;
        String eventName;
        Integer numberTickets;
        List<Integer> numticket = new ArrayList<Integer>();
        List<String> list = new ArrayList<String>();
        int[] numarray= new int[numticket.size()];
        String[] linesArray = list.toArray(new String[list.size()]);
        // Cycle through current events file line by line
        while((currentLine = buffRead.readLine()) != null) {
            if (currentLine.equals("END_________________00000")){
                break; // End of file
            }

            //Parse for event name & number of tickets
            eventName = currentLine.substring(0, currentLine.lastIndexOf("_")).trim();
            numberTickets = Integer.parseInt(currentLine.substring(currentLine.lastIndexOf
                    ("_") + 1));



            // Place event name and # tickets into data structure
            // Add event name to event array list with same index as # tickets
            // Parse int to get # tickets & add to arraylist for tickets with same index


             while((eventName = buffRead.readLine()) != null){
                   list.add(eventName);
                }


                for (int i =0 ; i< list.size();i++){

                    linesArray[i]= list.get(i);

                }




                 while((eventName = buffRead.readLine()) != null){
                       numticket.add(numberTickets);
                    }


                    for (int i =0 ; i< numticket.size();i++){

                        numarray[i]= numticket.get(i);

                    }

        }

        while(true) {
            consoleInput(linesArray, numarray, fileCurrentEvents);
        }
    } catch (IOException e) {
        System.out.println("File I/O Error"); //Print to console to signify error
        e.printStackTrace();
        System.exit(1);
    }



}

}

如果您在这一行收到 ArrayOutOfBoundsIndexException

File fileCurrentEvents = new File(args[0]);

那么大概意思就是你用的array(args)index(0)是越界因为它大于数组的大小。

如果你的数组看起来像

 [] //Zero entries

获取不到元素0(第一项),因为有none.

因此,当您 运行 代码时,您必须传入零参数。当你在命令行 运行 它时,在它后面添加文件名,或者在你的 IDE (Eclipse,IntelliJ,Sublime)中更改构建设置以将它添加到构建步骤中。

the error is being thrown on this line in the main method. File fileCurrentEvents = new File(args[0]);

那么你的 args 是空的(例如你的程序 运行 没有任何命令行参数,比如文件)。你可以添加一个默认值,比如

File fileCurrentEvents = new File(args.length > 0 ? args[0] : "default.txt");

在您的原始代码中,第 763 行实际上是:

for (int i = 0 ; i< list.size(); i++){

   linesArray[i] = list.get(i); //<--------------THIS ONE!

}

linesArraylist 短时会导致 ArrayIndexOutOfBoundsException。发生这种情况是因为您之前通过

实例化了 linesArray
 String[] linesArray = list.toArray(new String[list.size()]);

list 为空时,然后添加到 list 使其比您的数组长。

由于外部 while 循环似乎没有以任何其他方式使用 linesArray,您可能可以删除上面的 for 循环,并放置

 linesArray = list.toArray(new String[list.size()]);

在第一个 while 循环之后创建包含所有元素的适当数组。