因此,我创建了一个程序,该程序载入具有以下格式的文件: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();
}
}
也许你应该考虑使用正则表达式来拆分初始字符串。 – sinclair
这些行与您指定的格式不匹配。所以你要注意找到* real *规范,并且实现*那个。*否则,如果规范是正确的,则在运行时拒绝这些行。 – EJP
EJP,我在问怎么做。 – MrTumble