-4

I'm currently working on an assignment and have went through the workbook and java site multiple times and I can't seem to see where I got this wrong.

I am trying to import a file into a 2D Array. I am using Scanner w/ BufferedReader and FileReader to select a Command-Line argument (titanic.txt). I through in the //TEST if statement to see if it "fileInput" was still null. No issues while building, just while running.

Here is a portion of my code:

    //Declare Variables
    String[][] titanicArray = new String[1308][6];
    int[] classArray = new int[1308];
    int[] survivedIntArray = new int[1308];
    double[] ageArray = new double[1308];
    double[] ticketPriceArray = new double[1308];
    String inputFile = null;
    String answerStr = null;
    int answer1 = 0;

    Scanner fileInput = null;
    Scanner userInput = new Scanner(System.in);
    inputFile = args[0];

    //try statement to scan command-line argument and fill the array with the data
    try {
        fileInput = new Scanner(new BufferedReader(new FileReader(inputFile)));
        //TEST
        if (fileInput != null){
            System.out.println("Error Taking in file");
        }

        for (int row = 0; row < titanicArray.length; row++) {
            for (int col = 0; col < titanicArray[row].length; col++){
                while (fileInput.hasNext()){
                    titanicArray[row][col] = fileInput.next();
                }
            }
        }
    } finally {
        if (fileInput != null){
            System.out.println("Error Taking in file");
            fileInput.close();
        }//End of If for closing Scanner
    } //End of finally to close Scanner

NOTE: titanic.txt has data like below (Class, Suvived, Name, Sex, Age, TicketPrice) w/ tab and no blank-lines:

1 1 Allen, Miss. Elisabeth Walton female 29 211.3375

1 1 Allison, Master. Hudson Trevor male 0.9167 151.5500

1 0 Allison, Miss. Helen Loraine female 2 151.5500

1 0 Allison, Mr. Hudson Joshua Creighton male 30 151.5500

1 0 Allison, Mrs. Hudson J C (Bessie Waldo Daniels) female 25 151.5500

1 1 Anderson, Mr. Harry male 48 26.5500

1 1 Andrews, Miss. Kornelia Theodosia female 63 77.9583

2 Answers2

3
   if (fileInput != null){
        System.out.println("Error Taking in file");
    }

There seems to be an ovious mistake in your code: Why shoul fileInput != null be a problem? Anyway, it is always a good idea to clean up and simplify code first, then ask for help. Some ideas:

  • seperate file handling and file parsing into seperate methods
  • use try-with-resource to simplify Exception handling and resource closing
martinhh
  • 336
  • 2
  • 10
0

The size of array(columns) that you took is too small .next() gives you the first six strings only while the names in your input seem to be far too long.