java - 二维数组字符串分割错误

标签 java arrays

所以基本上我的程序采用一个文本文件并读取该文件并将其拆分为一个二维数组(文本文件: http://pastebin.com/6ACSUL20 )。我在命令行中传递文本文件的名称。但是,当我运行程序时,我收到 ArrayIndexOutOfBoundsException,这使我相信该程序没有正确分割文本文件。向我指出包含 Integer.parseInt(titanic[i][1]) 的每个方法,我们将不胜感激。

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


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */


public class Titanic {
    String[][] titanic;

    public Titanic(String[] args){
        try{
            File text = new File(args[0]);

            //turns the txt file into a string
            String content = new Scanner(text).useDelimiter("\\Z").next();

            //creates array and breaks up by new lines
            String[] rows = content.split("\n");

            // creates 2D array
            this.titanic = new String[rows.length][];

            // fills 2D array
            for(int i = 0; i < rows.length; i++){
                this.titanic[i] = rows[i].split("\\t");
            }// end for loop


        }// end try

        catch(FileNotFoundException e){
            System.out.println("Error" + e.getMessage());

        }// end catch method


    }// end fill method


    public void menu(){
        System.out.println("*******Welcome to the Titanic Statistical Application**************");
        System.out.println("");
        System.out.println("Enter the number of the question you want answered. Enter 'Q' to quit program:");
        System.out.println("");
        System.out.println("1. How many passengers were on the Titanic?");
        System.out.println("2. What percent of passengers perished on the Titanic?");
        System.out.println("3. What percent of passengers survived the sinking of the Titanic?");
        System.out.println("4. What percentage of passengers survived for each of the three classes?");
        System.out.println("5. What specific passengers who were less than 10 years old survived the sinking of the titanic?");
        System.out.println("6. For each letter in the alphabet, how many passengers last names started with that letter?");
        System.out.println("7. How many females and males were on the Titanic?");
        System.out.println("Q. Quit the program");
                }

    public void getPassengerNumber(){
        int num = titanic.length;
        System.out.println("There were " + num + " passengers on the Titanic.");
    }//end method

    public void getPerishedPercent(){
        int num = titanic.length;
        int perished = 0;

        for(int i = 0; i < num; i++){
            int x = Integer.parseInt(titanic[i][1]);
            if(x == 0){
                ++perished;

            }// end if
        }// end for
        double percent = (perished / num) * 100;
        System.out.println("The percentage perished on the Titanic is: " + percent);

    }// end method

    public void getPerishedSurvived(){
        int num = titanic.length;
        int survived = 0;

        for(int i = 0; i < num; i++){
            int x = Integer.parseInt(titanic[i][1]);
            if(x == 1){
                ++survived;

            }// end if
        }// end for
        double percent = (survived / num) * 100;
        System.out.println("The percentage survived on the Titanic is: " + percent);

    }// end method

    public void getClassPercentage(){
        int firstClass = 0;
        int secondClass = 0;
        int thirdClass = 0;
        int num = titanic.length;

        for(int i = 0; i < titanic.length; i++ ){
            int x = Integer.parseInt(titanic[i][0]);
            if(x == 1){
                ++firstClass;
            }// end iff
            if(x == 2){
                ++secondClass;
            }
            if(x == 3){
                ++thirdClass;
            }
        }// end for
      double firstpercent = (firstClass / num) * 100;
      double secondpercent = (secondClass / num) * 100;
      double thirdpercent = (thirdClass / num) * 100;

      System.out.println("Percent Survived for Firstclass is: " + firstpercent);
      System.out.println("Percent Survived for Secondclass is: " + secondpercent);
      System.out.println("Percent Survived for ThirdClass is: " + thirdpercent);

    }// end method

    public void getAge() {
        int num = titanic.length;
        int age = 0;

        for(int i = 0; i < num; i++ ){
            int x = Integer.parseInt(titanic[i][4]);
            if(x < 10){
                System.out.println(titanic[i][2]);
            }
        }// end for loop


    }// end method

    public void getLetters(){
        for(char a = 'A'; 'Z' <= a; a++ ){
           int temp = 0; 
           for(int i = 0; i < titanic.length; i++){
               char x = titanic[i][2].charAt(0);
               if(x == a){
                   ++temp;
               }// end if
            System.out.println(a + ": There are " + temp + " passengers that have this letter to start as their last name.");

           }// end inner
        } // end outer


    }// end method

    public void getGender(){
        int male = 0;
        int female = 0;
        int num = titanic.length;

        for(int i = 0; i < num; i++){
            if(titanic[i][3].equals("female")){
                ++female;
            }// end if
            if(titanic[i][3].equals("male")){
                ++male;
            }// end if
        }// end for

        System.out.printf("There were %d females and %d males on the titanic \n", male, female);
    }// end method


}//end class Titanic

使用该类来调用

package testtitanic;
import java.time.LocalTime;
import java.time.Duration;
import java.util.Scanner;
/**
 *
 * @author Joe
 */
public class TestTitanic {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] argv) {
        LocalTime startTime = LocalTime.now();
        Scanner input = new Scanner(System.in);
        int y = 1;
        Titanic data = new Titanic(argv);

        while(y == 1){
        data.menu();
        char x = input.next().charAt(0);
        switch (x){
            case '1':
                data.getPassengerNumber();
                break;
            case '2':
                data.getPerishedPercent();
                break;
            case '3':
                data.getPerishedSurvived();
                break;
            case '4':
                data.getClassPercentage();
                break;
            case '5':
                data.getAge();
                break;
            case '6':
                data.getLetters();
                break;
            case '7':
                data.getGender();
                break;
            case 'Q':
                y = 0;
                break;
            default:
                System.out.println("Please enter a valid input to exit, be sure to input a capital Q.");

        }// end switch



        }// end while loop











        LocalTime endTime = LocalTime.now();
        Duration timeElapsed = Duration.between(startTime,endTime);
        double time = timeElapsed.toMillis() * 1000;
        System.out.println("Thanks for running this program the total time elapsed is: " + time + " seconds");
    }

}

最佳答案

为我工作,但我在泰坦尼克号构造函数中硬编码了文件名。您确定要向其传递文件名吗?

你能发布堆栈跟踪吗?数组索引是否超出 argv 的范围?

您无需猜测索引出界的位置。堆栈跟踪将告诉您确切的行。

关于java - 二维数组字符串分割错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38298483/

相关文章:

java - 比较 Java 中的包装器类型

java - 嵌入式 jetty 是否支持 java 8 紧凑配置文件?

java - 覆盖java txt文件中的一行

javascript - KnockoutJS 无法从 observableArray 中删除对象

c - 如何通过函数更改数组

java - 我刚刚开始使用 jmathplot 并收到此异常消息

java - 将 ListView 和 ArrayAdapter 传递给另一个类

java - 递归方法打印太多次?

arrays - bash:如何删除函数内的列表条目?

php - OOP PHP MySQL 返回多行和变量