2D数组字符串拆分错误

时间:2016-07-11 02:50:41

标签: java arrays

基本上我的程序采用文本文件并读取文件并将其拆分为2D数组(文本文件: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");
    }

}

1 个答案:

答案 0 :(得分:0)

为我工作,但我在泰坦尼克号构造函数中硬编码了文件名。你确定你传给它一个文件名吗?

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

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