InputMismatchException в классе - PullRequest
       44

InputMismatchException в классе

0 голосов
/ 16 апреля 2020

У меня есть этот класс, который должен сканировать файл построчно и анализировать каждую строку, а затем распечатывать сведения о каждом из первых 10 пассажиров, отформатированные методом toString из другого класса.

package experiment9;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Paths;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
import java.text.DecimalFormat;
import java.util.stream.Stream;


public class Titanic {
    public static void main(String[] args) {
        ArrayList<Passenger>passengers = new ArrayList<Passenger>();
         try
         {
           Scanner file = new Scanner( new File( "titanic.csv" ) ); 
               while ( file.hasNext( ) ) // test for the end of the file
               {
                   // read a line
                   String line = file.nextLine( );

                   // process the line read
                   Scanner parse = new Scanner( line);
                   parse.useDelimiter( "," );
                   String firstName = parse.next( );
                   String lastName = parse.next( );
                   String gender = parse.next( );
                   String embarked = parse.next( );
                   String survived = parse.next( );
             try
             {
               double age = parse.nextDouble( );
               double fare = parse.nextDouble( );
               int Class = parse.nextInt( );

               Passenger prTemp = new Passenger( firstName, lastName, gender,
                         embarked, survived, age, fare, Class );

               // add Passenger object to passengers array list
               passengers.add( prTemp );  
             }

             catch ( InputMismatchException ime )
             {
                 System.out.println(ime);
                 ime.printStackTrace();
             }
           }

           // release resources associated with titanic.csv
           file.close( );
         }

         catch ( FileNotFoundException fnfe )
         {
           System.out.println( "Unable to find titanic.csv" );
         }

         catch ( Exception e )
         {
           e.printStackTrace( );
         }
                 //supposed to print out details of each 
                 //of the first 10 passengers (still working on this)
         for(int i=0; i<11;i++) {
             System.out.println(passengers.get(i).toString());
         }
        }

Моя основная проблема заключается в том, что в качестве выходных данных я получаю исключение InputMismatchException, которое все еще застряло при исправлении. Если вам нужна дополнительная информация, просто скажите мне. Любая помощь очень ценится. Что касается содержимого сканируемого файла, то здесь первые 11 или около того строк (во всем файле есть сотни строк):

last,first,gender,age,class,fare,embarked,survived
Braund,Mr. Owen Harris,M,22,3,7.25,Southampton,no
Cumings,Mrs. John Bradley (Florence Briggs Thayer),F,38,1,71.2833,Cherbourg,yes
Heikkinen,Miss Laina,F,26,3,7.925,Southampton,yes
Futrelle,Mrs. Jacques Heath (Lily May Peel),F,35,1,53.1,Southampton,yes
Allen,Mr. William Henry,M,35,3,8.05,Southampton,no
Moran,Mr. James,M,,3,8.4583,Queenstown,no
McCarthy,Mr. Timothy J,M,54,1,51.8625,Southampton,no
Palsson,Master Gosta Leonard,M,2,3,21.075,Southampton,no
Johnson,Mrs. Oscar W (Elisabeth Vilhelmina Berg),F,27,3,11.1333,Southampton,yes
Nasser,Mrs. Nicholas (Adele Achem),F,14,2,30.0708,Cherbourg,yes

Кроме того, вот класс с методом toString Я говорил о:

package experiment9;
import java.io.File;
import java.io.FileNotFoundException;
import java.text.DecimalFormat;
import java.util.Scanner;
import java.util.stream.Stream;
//Class Name
public class Passenger {

    //Instance fields
    String firstName;
    String lastName;
    String gender;
    String embarked;
    String survived;
    double age;
    double fare;
    int Class;

    //Constructor
    public Passenger(String firstName, String lastName, String gender,
                        String embarked,String survived, double age, double fare, int Class) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.gender = gender;
        this.embarked = embarked;
        this.survived = survived;
        this.age = age;
        this.fare = fare;
        this.Class = Class;
    }

    //toString Method
    public String toString() {

        DecimalFormat MONEY = new DecimalFormat("#0.00");

            if(age == -1) {
                return firstName + " " + lastName + "(" + gender + ")" + " from " + 
                        embarked + " paid " + MONEY.format(fare) + " pound for this trip at unknown age";
            }
                else    
            return firstName + " " + lastName + "(" + gender + ")" + " from " + 
                    embarked + " paid " + MONEY.format(fare) + " pound for this trip at the age of " + age;
    }
}
...