因此,我创建了一个程序,该程序加载具有以下格式的文件:John 55 18.27 然后将这三个变量(一旦拆分)传递到一个新创建的文件中。
我收到 1) Jack Turner 44 19.22 & 2) Mike 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);
}
}
公共(public)类 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();
}
}
最佳答案
一、看完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());
关于java - 异常处理和 IO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34912077/