简体   繁体   English

从 txt 文件中提取数据获取 java.lang.Arrayindexoutofboundsexception 错误

[英]pulling data from txt file getting java.lang.Arrayindexoutofboundsexception errors

can someone please help me figure out what the indexes should be to get this to run fully I've tried all kinds of fixes and nothing is working properly.有人可以帮我弄清楚索引应该是什么才能让它完全运行我已经尝试了各种修复,但没有任何工作正常。 I have a feeling that the issue is in the first declaration of data String[][] data = new String[MAXPASSENGERS][6];我有一种感觉,问题出在data String[][] data = new String[MAXPASSENGERS][6];的第一个声明中String[][] data = new String[MAXPASSENGERS][6]; First error is here:第一个错误在这里:

int status = Integer.parseInt(data[i][1]);

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1` at Titanic.getTotalNumberofPerishedPassengers(Titanic.java:43)1线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 1` at Titanic.getTotalNumberofPerishedPassengers(Titanic.java:43)1

Second error is here:第二个错误在这里:

int status = Integer.parseInt(data[i][1]);

and here和这里

return getTotalPassengers() - getTotalNumberofPerishedPassengers();

with these errors有这些错误

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at Titanic.getTotalNumberofPerishedPassengers(Titanic.java:43)线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 1 at Titanic.getTotalNumberofPerishedPassengers(Titanic.java:43)

and

return getTotalPassengers() - getTotalNumberofPerishedPassengers();

Third error:第三个错误:

int status = Integer.parseInt(data[i][1]);

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1, at TItanic.getTotalNumberofSurvivedPassengerByClass(Titanic.java:71)线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 1, at TItanic.getTotalNumberofSurvivedPassengerByClass(Titanic.java:71)

How do I fix these to make my code run properly?如何修复这些问题以使我的代码正常运行? I've tried changing the array value, but that doesn't do anything and I get the same incorrect results.我试过更改数组值,但这没有任何作用,而且我得到了相同的错误结果。

/**

* file: TestTitanic.java Author: Date: 8May15 */ import java.util.Scanner; * 文件:TestTitanic.java 作者:日期:8May15 */ import java.util.Scanner;

/* TestTitanic used to test the titanic data */ public class TestTitanic { /* TestTitanic 用于测试泰坦尼克号数据 */ public class TestTitanic {

public static void main(String[] args) {

    String fileName = "";
    Titanic titanic = null;

    //Get the file name from command line arguments
    if (args.length > 0) {
        fileName = args[0];
    } else {
        fileName = "titaniiiic.txt";
    }

    // Check the file and create titanic statistics
    try {
        titanic = new Titanic(fileName);
    } catch (Exception ex) {
        System.out.println("File not found");
        System.exit(1);
    }

    //The application should keep track of the elapsed time (in seconds) 
    long startTime = System.currentTimeMillis();

    //A user-friendly and well-organized menu s
    String choices[] = {"Total number of passengers on the Titanic",
        "Total number of passengers who perished on the Titanic",
        "Total number of Passengers who survived the sinking of the Titanic",
        "Number of passengers who survived the sinking of the Titanic as a function of the passenger class (e.g. 1,2,3)",
        "Number of passengers who survived the sinking of the Titanic as a function of the passenger gender (e.g., male, female)",
        "A list of the names of passengers who paid greater than $200 for their tickets",
        "A list of the names of passengers who were less than 10 years old who survived",
        "A list of the names of passengers who were less than 10 years old who perished ",
        "The count of the number of passengers as a function of the first letter of their last name. (e.g., A: 13, B:33 …)", "Exit"
    };

    int choice = menuChoice(choices);
    while (choice != 10) {
        switch (choice) {
            case 1:
                System.out.println("Total number of passengers on the Titanic: " + titanic.getTotalPassengers());
                break;
            case 2:
                System.out.println("Total number of passengers who perished on the Titanic: " + titanic.getTotalNumberofPerishedPassengers());
                break;
            case 3:
                System.out.println("Total number of passengers who survived : " + titanic.getTotalNumberofSurvivedPassengers());
                break;
            case 4:
                System.out.print("Enter class (e.g. 1,2,3): ");
                int cls = getIntInRange(1, 3);
                System.out.println(cls + " class number of passengers who survived: " + titanic.getTotalNumberofSurvivedPassengersByClass(cls));
                break;
            case 5:
                System.out.print("Names of passengers who were less than 10 years old who survived: ");
                System.out.println(titanic.getSurvivedNamesLessGivenAge(10));
                break;
            case 6:
                System.out.print("Enter the letter: ");
                char ch = getString().charAt(0);
                System.out.println("Count: " + titanic.getCountByFirstLetterOfFirstName(ch));
                break;
        }
        choice = menuChoice(choices);
    }

    //The application should keep track of the elapsed time (in seconds) 
    long endTime = System.currentTimeMillis();
    long elapsedTime = (endTime - startTime) / 1000;
    /**
     * After the program is exited, the application should provide a prompt
     * thanking the user for trying the Titanic program and providing the
     * total time elapsed.
     */
    System.out.println("Thank you for trying the Titanic program");
    System.out.println("Elapsed time: " + elapsedTime);
}

/**
 * Helper method to get String from user
 *
 * @return
 */
public static String getString() {
    Scanner input = new Scanner(System.in);
    return input.nextLine();
}

/**
 * Helper method to get user input in range
 *
 * @param low
 * @param high
 * @return
 */
public static int getIntInRange(int low, int high) {
    int num = 0;
    do {
        num = getInt();
        if (num < low || num > high) {
            System.out.println("Enter number between " + low + " and " + high);
        }
    } while (num < low || num > high);
    return num;
}

/**
 *
 * method to display organized menu to user
 *
 * @param choices
 * @return
 */
public static int menuChoice(String choices[]) {
    int choice = 0;
    System.out.println("");
    for (int i = 0; i < choices.length; i++) {
        System.out.println((i + 1) + ". " + choices[i]);
    }
    System.out.print("Enter choice (1-" + choices.length + "): ");
    choice = getIntInRange(1, choices.length);
    return choice;
}

/**
 * Helper method to get int from user
 *
 * @return
 */
    public static int getInt() {
        Scanner input = new Scanner(System.in);
        int num = -1;
        boolean good;
            do {
            good = true;
            try {
                num = input.nextInt();
            } catch (Exception e) {
            good = false;
                input = new Scanner(System.in);
                System.out.println("Enter numeric value: ");
            }
        } while (!good);
        return num;
    }
}

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

 // java class Titanic
public class Titanic {

    int MAXPASSENGERS = 10000;
    int actualPassengers = 0;
    //B. Use a 2D array to store the Titanic data. 
    String[][] data = new String[MAXPASSENGERS][6];

    /**
     * Constructor to read file and set 2D array to store the Titanic data
     */
    Titanic(String filename) throws FileNotFoundException {
        Scanner fileReader = new Scanner(new File(filename));

        while (fileReader.hasNextLine()) {
            //line has tab delimeted data
            data[actualPassengers++] = fileReader.nextLine().split("\t");

        }
        fileReader.close();
    }

    /**
     *
     * @return Total number of passengers on the Titanic
     */
public int getTotalPassengers() {
        return actualPassengers;
    }

    /**
     *
     * @return Total number of passengers who perished on the Titanic
     */
    public int getTotalNumberofPerishedPassengers() {
        int count = 0;
        for (int i = 0; i < getTotalPassengers(); i++) {

            int status = Integer.parseInt(data[i][1]);
            //Survived (1=yes, 0=no)
            if (status == 0) {
                count++;
            }
        }
        return count;
    }

    /**
     *
     * @return Total number of Passengers who survived the sinking of the
     * Titanic
     */
    public int getTotalNumberofSurvivedPassengers() {
        return getTotalPassengers() - getTotalNumberofPerishedPassengers();
    }

    /**
     * Number of passengers who survived the sinking of the Titanic as a
     * function of the passenger class (e.g. 1,2,3)
     *
     * @param cls
     * @return
     */
    public int getTotalNumberofSurvivedPassengersByClass(int cls) {
        int count = 0;
        for (int i = 0; i < getTotalPassengers(); i++) {
            int status = Integer.parseInt(data[i][1]);
            int clazz = Integer.parseInt(data[i][0]);
            //Survived (1=yes, 0=no)
            if (status == 1 && clazz == cls) {
                count++;
            }
        }
        return count;
    }

    /**
     * Number of passengers who survived the sinking of the Titanic as a
     * function of the passenger gender (e.g., male, female)
     *
     * @param cls
     * @return
     */
    public int getTotalNumberofSurvivedPassengersByGender(String gender) {
        int count = 0;
        for (int i = 0; i < getTotalPassengers(); i++) {
            int status = Integer.parseInt(data[i][1]);
            //Survived (1=yes, 0=no)
            if (status == 1 && gender.equalsIgnoreCase(data[i][3])) {
                count++;
            } 
        }
        return count;
     }

    /**
     *
     * @param cls
     * @return A list of the names of passengers who paid greater than given
     * fair for their tickets
     */
    public String getNamesPaidFare(double fair) {
        String name = "";
        for (int i = 0; i < getTotalPassengers(); i++) {
            if (data[i].length >= 6) {
            double pfair = Double.parseDouble(data[i][5]);
            if (pfair > fair) {
                name += "\n" + data[i][2];
            }
        }
    }
    return name;
}

/**
 * G. A list of the names of passengers who were less than 10 years old who
 * survived the sinking of the Titanic
 *
 * @param fair
 * @return
 */
public String getSurvivedNamesLessGivenAge(int age) {
    String name = "";
    for (int i = 0; i < getTotalPassengers(); i++) {
        if (data[i].length >= 6 && data[i][4].length()>0) {
                int status = Integer.parseInt(data[i][1]);
                double pAge = Double.parseDouble(data[i][4]);
            //Survived (1=yes, 0=no)
            if (status == 1 && pAge < age) {
                name += "\n" + data[i][2];
            }
        }
    }
    return name;
}

/**
 * H. A list of the names of passengers who were less than 10 years old who
 * perished on the Titanic
 *
 * @param fair
 * @return
 */
public String getPerishedNamesLessGivenAge(int age) {
   String name = "";
    for (int i = 0; i < getTotalPassengers(); i++) {
        if (data[i].length >= 6 && data[i][4].length()>0) {
            int status = Integer.parseInt(data[i][1]);
            double pAge = Double.parseDouble(data[i][4]);
            //Survived (1=yes, 0=no)
            if (status ==0 && pAge < age) {
                name += "\n" + data[i][2];
            }
        }
    }
    return name;
}

/**
 * The count of the number of passengers as a function of the first letter
 * of their last name. (e.g., A: 13, B:33 …)
 *
 * @param ch
 * @return
 */
public int getCountByFirstLetterOfFirstName(char ch) {
    int count = 0;
    for (int i = 0; i < getTotalPassengers(); i++) {
        char pChar = data[i][2].charAt(0);

        if (Character.toUpperCase(ch) == Character.toUpperCase(pChar)) {
            count++;
        }
    }
    return count;
}

} }

so i figured out the fix to the ArrayIndexOutOfBounds errors and got it to work.所以我想出了对 ArrayIndexOutOfBounds 错误的修复并让它工作。 The only remaining issue with the above programs is that answering question 4 (survivors by class).上述程序唯一剩下的问题是回答问题 4(按类别的幸存者)。 Here's the code for that portion of the Titanic.java class that works:下面是 Titanic.java 类的那部分工作的代码:

    /**
     * Number of passengers who survived the sinking of the Titanic as a
     * function of the passenger class (e.g. 1,2,3)
     *
     * @param cls
     * @return
     */
    public int getTotalNumberofSurvivedPassengersByClass(int cls) {
        int count = 0;
        for (int i = 0; i < getTotalPassengers(); i++) {
            int status = Integer.parseInt(data[i][1]);
            int clazz = Integer.parseInt(data[i][0]);
            //Survived (1 = yes, 0 = no)
            if (status == 1 && clazz == cls) {
                count++;
            }
        }
        return count;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM