2016-01-20 109 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新增。 –