因此,我創建了一個程序,該程序載入具有以下格式的文件: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