这是主要类,当我输入1或2进行下一步时,它适用于第一步,它会给出错误说"错误读取文件
public static void main(String [] args)抛出IOException {
Scanner sc = new Scanner(System.in);
System.out.println("1.Fraction Calculator");
System.out.println("2.Grading Scheme");
System.out.println("Enter Your Choice:");
int ip = sc.nextInt();
String frac1, frac2;
// creating an object of Fraction class
Grading grad=new Grading();
grad.readFile();
grad.calculateAverage();
grad.calculateTestAvg();
// creating an object of Fraction class
Fraction frac =new Fraction();
switch(ip){
case 1: System.out.println("Enter two fractions:");
// input of the two fractions
frac1 = sc.next(); frac2 = sc.next();
// displaying the result table
System.out.println("Addition: " + frac.add(frac1, frac2) + "\nSubtraction: " + frac.sub(frac1,frac2) + "\nMultiplication: " + frac.mul(frac1,frac2) + "\nDivision: " + frac.div(frac1, frac2));
break;
case 2: grad.printGrades(); break;
default : break;
}
}
答案 0 :(得分:1)
您必须使用throws FileNotFoundException
FileReader
,因此您有两个选项:
void Grading() throws FileNotFoundException {
FileReader fr = new FileReader("score.txt");
BufferedReader br = new BufferedReader(fr);
}
或使用try{}catch(){}
:
void Grading() {
FileReader fr;
try {
fr = new FileReader("score.txt");
} catch (FileNotFoundException ex) {
//...
}
BufferedReader br = new BufferedReader(fr);
}
修改强>
请勿忘记导入此库:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
答案 1 :(得分:1)
因为你没有处理java.io.FileNotFoundException, 你可以抛出异常或使用try catch块来处理它
抛出异常
void Grading()throws FileNotFoundException{
FileReader fr = new FileReader("score.txt");
BufferedReader br = new BufferedReader(fr);
}
<强>的try-catch 强>
void Grading(){
FileReader fr = null;
try {
fr = new FileReader("score.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader br = new BufferedReader(fr);
}