简体   繁体   中英

Getting different data types from each line in a text file

Edit: Only thing not working now is the following code for option number 7. The ages in passenger[i][4] are in either a integer or float type. The program begins to print out the names of the people who are less than 10 years old but stops after it prints a int instead of a float. The program exits right after that.

public int getPassWhoYoung() {

        System.out.println("The passengers younger than 10:");
        int count = 0;
        for(int i = 0; i < passengers.length; i++){
            if(passengers[i][4] != null && passengers[i][1].equals("1")){
                double x = Double.valueOf(passengers[i][4]);
                if(x < 10){
                    System.out.println(passengers[i][2]);
                }
                count++;
            }
        }
        System.out.println("The passengers under 10 who survived: ");

        return count;
    }

Original Problem: I am trying to make a program that uses a loop to read each line of a text file and separate each data type. With that in mind, each line does not contain every data type. Each line is a different passenger on the Titanic. The first number is the class they were in, the second number was if they lived of died (0 if they died, 1 if they lived), their name(last, title, first, middle), gender, age, and price they paid for their ticket. Here is the first line of the file: "1 1 Allen, Miss. Elisabeth Walton female 29 211.3375"

This is my mess in progress so far: main

import java.time.Duration;
import java.time.Instant;
import java.util.Scanner;
import java.io.*;

public class TitanicProgram {

    public static void main(String[] args) throws IOException  {
        String choice;
        boolean loop = true;
        String titanicFile = "Titanic.txt";
        Scanner scannerIn = new Scanner(System.in);
         // Uses Time at start
        Instant before = Instant.now();




        Passenger p = new Passenger(titanicFile);

        System.out.println("********** Welcome to the Titanic Statistical" +
                    " Application **************************");

        while (loop == true) {

            System.out.println("Enter the number of the question you want answered."
                    + " Enter ‘Q’ to quit the program :\n" 
                    + "1. How many passengers were on the Titanic?\n" +
                    "2. What percentage of passengers perished on the Titanic?\n" +
                    "3. What percentage passengers survived the sinking of the Titanic?\n" +
                    "4. What percentage of passengers survived for each of the three classes?\n" +
                    "5. What percentage of passengers survived as a function of gender?\n" +
                    "6. What specific passengers paid more than $200 for their tickets?\n" +
                    "7. What specific passengers who were less than 10 years old perished on the titanic?\n" +
                    "8. What specific passengers who were less than 10 years old survived the sinking of the titanic?\n" +
                    "9. For each letter in the alphabet, how many passengers last names started with that letter?\n" +
                    "Q. Quit the program\n\n" + "Enter your selection: ");
            choice = scannerIn.nextLine();
            switch (choice) {
                case "1": System.out.println("The total number of passengers: "
                        + p.readLines() + "\n");
                    break;
                case "2": System.out.println("2!");
                    break;
                case "3": System.out.println("3!");
                    break;
                case "4": System.out.println("4!");
                    break;
                case "5": System.out.println("5!");
                    break;
                case "6": System.out.println("6!");
                    break;
                case "7": System.out.println("7!");
                    break;
                case "8": System.out.println("8!");
                    break;
                case "9": System.out.println("9!");
                    break;
                case "Q": System.out.println("Thank you for trying the" + 
                        " Titanic Program!");
                    loop = false;
                    break;
                default: System.out.println("Enter a valid Option!");
            }
        }
        Instant after = Instant.now();
        System.out.println("Elapsed time in seconds was: " +
        Duration.between(before, after).toNanos()/1_000_000_000.0);
    }

}

Here is the Passenger class (I know it's really bad, it's in progress):

package titanicprogram;

import java.io.*;
import java.util.Scanner;


// I am still working on this, not too much progress yet
public class Passenger {
    private int totalPass = 0;
    private int passWhoDied = 0;
    private int passWhoLived = 0;
    private int malePassLived = 0;
    private int femalePassLived = 0;
    private String namePassCost;
    private String nameKidsDied;
    private String nameKidsLived;
    // Testing
    private int passClass;
    private int passSurvived;
    private String lastName;
    private String passTitle;
    private String firstName;
    private String midName;
    private String genderFemale;
    private String genderMale;
    private int age;
    private float price;


    //private String[] lastNames;
    private Scanner scan;
    private String path;

    public Passenger(String filePath) {
        path = filePath;
    }

    public String[] OpenFile() throws IOException {
        FileReader fr = new FileReader(path);
        BufferedReader textReader = new BufferedReader(fr);
        int numberOfLines = readLines();
        String[ ] textData = new String[numberOfLines];
        for (int i=0; i < numberOfLines; i++) {
            textData[ i ] = textReader.readLine();
            textData[i] = textReader.readLine( );
        }
        textReader.close( );
        return textData;
    }

    public int readLines() throws IOException {
        FileReader fr1 = new FileReader(path);
        BufferedReader textReader1 = new BufferedReader(fr1);
        String eachLine;
        int numberOfLines = 0;
        while ( ( eachLine = textReader1.readLine( ) ) != null ) {
            numberOfLines++;
        }
        while(scan.hasNext()){

            if (scan.hasNextInt()) {
                passClass = scan.nextInt();
            }
            if (scan.hasNextInt()) {
                passSurvived = scan.nextInt();
            } else {
                scan.next();
            }/*
            passClass = scan.nextInt();
            passSurvived = scan.nextInt();
            lastName = scan.next();
            passTitle = scan.next();
            firstName = scan.next();
            midName = scan.next();
            genderFemale = scan.findInLine("female");
            genderMale = scan.findInLine("male");
            age = scan.nextInt();
            price = scan.nextFloat();

            System.out.printf(passTitle, lastName);
                    */
        }
        return numberOfLines;
    }







    /*
    public void openFile(){
        try{
            scan = new Scanner(new File("Titanic.txt"));
        }
        catch(Exception e){
            System.out.println("File not found!");
        }
    }

    public void readFile() throws IOException {



        while(scan.hasNext()){


            int passClass = scan.nextInt();
            int passSurvived = scan.nextInt();
            String lastName = scan.next();
            String passTitle = scan.next();
            String firstName = scan.next();
            String midName = scan.next();
            String genderFemale = scan.findInLine("female");
            String genderMale = scan.findInLine("male");
            int age = scan.nextInt();
            float price = scan.nextFloat();

            System.out.printf(passTitle, lastName);

        }
    }

    public void closeFile() {
        scan.close();
    }
    */

    // Getter methods
    public int getTotalPass() {
        return totalPass;
    }

    public int getPassWhoDied() {
        return passWhoDied;
    }

    public int getPassWhoLived() {
        return passWhoLived;
    }

    public int getMalePassLived() {
        return malePassLived;
    }

    public int getFemalePassLived() {
        return femalePassLived;
    }

    public String getNamePassCost() {
        return namePassCost;
    }

    public String getNameKidsDied() {
        return nameKidsDied;
    }

    public String getNameKidsLived() {
        return nameKidsLived;
    }
}

Try This. I used the StringTokenizer makes things easier and more intuitive.

    //USE MAP FOR SAVE PEOPLE
    private static Map<String, Integer> passengers;
    private static BufferedReader innerReader;

public static List<String> loadFile(Reader reader)
        throws IllegalArgumentException, IOException {

    //YOU CAN REPLACE STRING WITH YOURS CUSTOM TYPE
    List<String> fileList = new ArrayList<String>();
    //INITIALIZE MAP
    passengers = new HashMap<String, Integer>();

    if(reader == null)
    {
        throw new IllegalArgumentException("Reader non valido");
    }
    innerReader = new BufferedReader(reader);
    String line;
    try
    {
    while((line = innerReader.readLine()) != null)
    {
        if (line == null || line.trim().isEmpty())
            throw new IllegalArgumentException(
                    "Line Empty");

        StringTokenizer tokenizer = new StringTokenizer(line);
        int classInt, liveOrDeadInt, ageInt;
        double priceDouble;
        String classes = tokenizer.nextToken(" ").trim();
        String liveOrDead = tokenizer.nextToken(" ").trim();
        String lastName = tokenizer.nextToken(",").trim();
        String titleName = tokenizer.nextToken(",.").trim();
        String firstName = tokenizer.nextToken("\\. ").trim();
        String middleName = tokenizer.nextToken("\\. ").trim();
        String gender = tokenizer.nextToken("0123456789").trim();
        String age = tokenizer.nextToken(" ").trim();
        String price = tokenizer.nextToken("\n\r").trim();
        StringBuilder sb = new StringBuilder();

        //IF YOU WOULD CHECK NUMBER CONVERSION DO
        try
        {
            classInt = Integer.parseInt(classes);
        }catch(Exception e){
            throw new IllegalArgumentException(e);
        }
        try
        {
            liveOrDeadInt = Integer.parseInt(liveOrDead);
        }catch(Exception e){
            throw new IllegalArgumentException(e);
        }
        try
        {
            ageInt = Integer.parseInt(age);
        }catch(Exception e){
            throw new IllegalArgumentException(e);
        }
        try
        {
            priceDouble = Double.parseDouble(price);
        }catch(Exception e){
            throw new IllegalArgumentException(e);
        }
        //CHECK IF ARE ALIVE AND HAVE LESS THAN 10 YEARS
        if(ageInt < 10 && liveOrDeadInt == 1)
        {
            sb.append(lastName + ", " + titleName +
                ". " + firstName + " " + middleName);
            passengers.put(sb.toString(), ageInt);
        }
        //EMPTY STRING BUILDER
        sb.delete(0, sb.length());

        sb.append(classes + " " + liveOrDead + " " + lastName + ", " + titleName +
                ". " + firstName + " " + middleName + " " + gender + " " + age +
                " " + price);
        //READ FILE SUCCESS
        fileList.add(sb.toString());

    }
    } catch (NoSuchElementException | NumberFormatException e) {
        throw new IllegalArgumentException(e);
    }
    return fileList;
}

public static void close() {
    try {
        innerReader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

With This Main:

        List<String> test = new ArrayList<String>();
    try {
        test = loadFile(new FileReader("FileName.txt"));
    } catch (IllegalArgumentException | IOException e) {
        e.printStackTrace();
    }
    close();
    for(String s : test)
    {
        System.out.println(s);
    }
    //SHOW PASSENGERS WHO SURVIVED
    System.out.println("The passengers under 10 who survived: ");
     Iterator it = passengers.entrySet().iterator();
      while (it.hasNext()) {
        Map.Entry entry = (Map.Entry)it.next();
        System.out.println(entry.getKey() + "  Age:" + entry.getValue());
        }
      System.out.println("Total passengers under 10 who survived: " + passengers.size());
    //OR USE METHOD
    showPassengers();

Or do this:

public static void showPassengers()
{
    System.out.println("The passengers under 10 who survived: ");
     Iterator it = passengers.entrySet().iterator();
      while (it.hasNext()) {
        Map.Entry entry = (Map.Entry)it.next();
        System.out.println(entry.getKey() + "  Age:" + entry.getValue());
        }
      System.out.println("Total passengers under 10 who survived: " + passengers.size());
}

Make this new output:

1 1 Allen, Miss. Elisabeth Walton female 29 211.3375

1 1 Allen, Miss. Elisabeth Walton female 29 211.3375

1 0 Allen, Miss. Eli Walton female 9 211.3375

1 1 Allen, Miss. Elisabeth Walton female 29 211.3375

1 1 Allen, Miss. Elisabeth Walton female 29 211.3375

1 1 Allen, Miss. Elisabeth Walton female 7 211.3375

1 1 Allen, Mrs. Elisabeth Walton female 3 211.3375

1 1 Allen, Miss. Elisabeth Wally female 9 211.3375

The passengers under 10 who survived:

Allen, Miss. Elisabeth Wally Age:9

Allen, Miss. Elisabeth Walton Age:7

Allen, Mrs. Elisabeth Walton Age:3

Total passengers under 10 who survived: 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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