从文本文件中的每一行获取不同的数据类型

时间:2015-07-11 14:21:32

标签: java file-io integer double text-files

编辑:现在唯一不起作用的是选项编号7的以下代码.persenger [i] [4]中的年龄是整数或浮点类型。该程序开始打印出小于10岁的人的名字,但在打印出int而不是浮动之后停止。该程序在此之后立即退出。

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;
    }

原始问题: 我正在尝试创建一个程序,使用循环来读取文本文件的每一行并分隔每种数据类型。考虑到这一点,每行不包含每种数据类型。每条线路都是泰坦尼克号上的不同乘客。第一个数字是他们所在的班级,第二个数字是他们是否死了(0如果他们死了,1他们住了),他们的名字(姓氏,头衔,头等,中间),性别,年龄和价格他们支付了他们的机票。这是文件的第一行:&#34; 1 1 Allen,Miss.Elisabeth Walton女29 211.3375&#34;

到目前为止,这是我的进展: 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);
    }

}

这是乘客班(我知道它非常糟糕,它正在进行中):

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;
    }
}

1 个答案:

答案 0 :(得分:1)

试试这个。我使用StringTokenizer使事情变得更容易和更直观。

    //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();
    }
}

使用此主菜:

        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();

或者这样做:

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());
}

制作这个新输出:

  <1> 1艾伦,小姐。伊丽莎白沃尔顿女29 211.3375

     <1> 1艾伦,小姐。伊丽莎白沃尔顿女29 211.3375

     

1 0 Allen,Miss.Eli Walton女9 211.3375

     <1> 1艾伦,小姐。伊丽莎白沃尔顿女29 211.3375

     <1> 1艾伦,小姐。伊丽莎白沃尔顿女29 211.3375

     <1> 1艾伦,小姐。伊丽莎白沃尔顿女7 211.3375

     <1> 1艾伦,伊丽莎白女士沃尔顿女士3 211.3375

     <1> 1艾伦,小姐。伊丽莎白沃利女9 211.3375

     

幸存下来的10岁以下乘客:

     

Allen,Miss.Elisabeth Wally年龄:9

     

Allen,Miss.Elisabeth Walton年龄:7

     艾伦,伊丽莎白沃尔顿夫人年龄:3

     

幸存的10岁以下乘客总数:3