2016-01-20 151 views
0

因此,我創建了一個程序,該程序載入具有以下格式的文件:John 55 18.27然後將這三個變量(一旦拆分)傳遞到新創建的文件中。異常處理和IO

我得到一個異常錯誤1)傑克·特納44 19.22 & 2)邁克55.0 23.44 第一個錯誤是因爲姓,另一個是像55.0 整我怎樣才能解決我的代碼來處理這些異常?

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


public class methods { 
    private String name; 
    private int hours; 
    private double timeSpent; 
    private double averageGPA; 

    private Scanner x; 
    private StringTokenizer stk; 
    private String[] storage = new String[11]; 
    private Formatter file; 

    public void openFile(){ 
     try{ 
      x = new Scanner(new File("students.dat")); 
     } 
     catch(Exception e){ 
      System.out.println("could not find file"); 
     } 
    } 

    public void readFile(){ 
     int count = 0; 
     while(x.hasNext()){ 

      storage[count] = x.nextLine(); 
      count ++; 
     } 
    } 

    public void closeFile(){ 
     x.close(); 
    } 

    public void stringTokenizer(){ 
     int count = 0; 
     createNewFile(); 
     while(count < storage.length){ 

     stk = new StringTokenizer(storage[count]); 
     name = stk.nextToken(); 
     hours = Integer.parseInt(stk.nextToken()); 
     timeSpent = Double.parseDouble(stk.nextToken()); 
     addRecords(); 
     count++; 

     } 
     file.close(); 

    } 

    public void createNewFile(){ 
     try{ 
      file = new Formatter("skeleton.txt"); 
     } 
     catch(Exception e){ 
      System.out.println("There has been an error"); 
     } 
    } 

    public void addRecords(){ 
     file.format("%s %s %s\n", name, hours, timeSpent); 
    } 

} 

公共類Lab1_a {

public static void main(String[] args) { 
    int creditHrs;  // number of semester hours earned 
double qualityPts; // number of quality points earned 
double gpa;  // grade point (quality point) average 

String line, name = "", inputName = "students.dat"; 
String outputName = "warning.dat"; 

    //Get File 
    methods obj1 = new methods(); 


    //Create an Array of Strings 
    obj1.openFile(); 
    obj1.readFile(); 



    obj1.createNewFile(); 
    obj1.stringTokenizer(); 
    obj1.closeFile(); 
} 

}

+0

也許你應該考慮使用正則表達式來拆分初始字符串。 – sinclair

+0

這些行與您指定的格式不匹配。所以你要注意找到* real *規範,並且實現*那個。*否則,如果規範是正確的,則在運行時拒絕這些行。 – EJP

+0

EJP,我在問怎麼做。 – MrTumble

回答

0

首先,閱讀name後,如果下一個標記不能被解析爲double,它與之間的空間追加到name。繼續,直到找到double

一旦找到第一個double,將其轉換爲int並存儲爲hours

解析timeSpent像以前一樣。

這裏的一些(未經測試)的代碼,應該讓你開始:

name = stk.nextToken(); 
String next; 
while (true) { 
    try { 
     next = stk.nextToken(); 
     hours = (int)Double.parseDouble(next); 
     break; 
    } catch (NumberFormatException e) { 
     name = name + " " + next; 
    } 
} 
timeSpent = Double.parseDouble(stk.nextToken()); 
+0

你能告訴我一些關於如何做的代碼嗎? – MrTumble

+0

@MrTumble新增。 –