2015-07-11 79 views
1

編輯:唯一現在不工作爲選項號7中乘客的年齡[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,如果他們住),他們的名字(最後,標題,第一,中),性別,年齡和價格他們爲他們的票支付。下面是該文件的第一行:「1·艾倫,小姐伊麗莎白·沃爾頓女29 211.3375。」

這是我進步的混亂至今: 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

試試這個。我使用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("").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 - 阿倫,小姐伊麗莎白·沃爾頓女29 211.3375

1 1阿倫,小姐。伊麗莎白沃爾頓女29 211.3375

1 0阿倫,小姐。禮沃爾頓雌性9 211.3375

1 1阿倫,小姐。伊麗莎白沃爾頓女29 211.3375

1 1艾倫小姐。伊麗莎白沃爾頓女29 211.3375

1 1阿倫,小姐。伊麗莎白沃爾頓女7 211.3375

1 1阿倫,伊麗莎白沃爾頓夫人女性3 211.3375

艾倫小姐伊麗莎白·沃利年齡:9

艾倫小姐伊麗莎白·沃爾頓時代

1 - 阿倫,小姐伊麗莎白·沃利女9 211.3375

誰倖存的10歲以下的乘客: 7

阿倫,夫人伊麗莎白·沃爾頓年齡:3名

下10總乘客誰存活:現在3

+0

確定一切正常但有一個例外。對於選項7我有這樣的代碼: – Bill

+0

我更新並調整了一些東西,現在試試 –