这是我的代码的基础。它在控制台上打印学生成绩,但如何使用Buffereader将所有学生成绩放在新文件上。
import java.io.*;
import java.util.InputMismatchException;
import java.lang.*;
import java.util.*;
public class WorkSpace {
private Scanner x;
public void openFile(){
try{
x = new Scanner (new File ("grades.txt"));
}
catch(Exception e){
System.out.println("could not find file");
}}
public void createFile()throws IOException {
try{
File file = new File("grades.txt");
Scanner s = new Scanner(file);
while(s.hasNext()){
{
String [] split = s.nextLine().split(", ");
String fname = split[0];
Double q1 = Double.parseDouble (split[1]);
Double q2 = Double.parseDouble (split[2]);
Double q3 = Double.parseDouble (split[3]);
Double q4 = Double.parseDouble (split[4]);
Double proji = Double.parseDouble (split[5]);
Double projii = Double.parseDouble (split[6]);
Double projiii = Double.parseDouble (split[7]);
double studentgrade = (q1 *0.1) + (q2 *0.1) +(q3 *0.1) + (q4 *0.1) +(proji*0.15) + (projii * 0.2) + (projiii *0.25);
if(studentgrade>90)
System.out.printf("%s got an A\n", fname);
else if(studentgrade>80)
System.out.printf("%s got a B\n", fname);
else if(studentgrade>70)
System.out.printf("%s got a C\n", fname);
else if(studentgrade>60)
System.out.printf("%s got a D\n", fname);
else if(studentgrade>50)
System.out.printf("%s got a F\n", fname);
}}}catch(Exception e){
e.printStackTrace();
}
}
public void closeFile(){
x.close();
}
答案 0 :(得分:0)
您如何阅读文件不正确。使用扫描仪读取文件的最常用方法:
try{
File file = new File("Your/File/Path");
Scanner s = new Scanner(file);
s.useDelimiter("\n");//splits the whole file's text by "\n"
while(s.hasNext()){
String next = s.next();
//parse your stuff
}
s.close();
}catch(Exception e){}
此外,try{
File file = new File("Your/File/Path");
Scanner s = new Scanner(file);
s.useDelimiter("\n");//splits the whole file's text by "\n"
while(s.hasNext()){
String next = s.next();
//parse your stuff
}
s.close();
}catch(Exception e){}
不会返回文件的长度。那就是问题所在。使用scanner.nextInt()
获取文件的长度。
答案 1 :(得分:0)
Scanner.nextInt()返回从源读取的下一个整数值(不是源长度或其他东西)。您打开文件并尝试在开头读取整数,但该文件不以整数开头,因此您将获得异常。
答案 2 :(得分:0)
你的问题没有意义。 BufferedReader
不会写文件。它,错误,读取文件。你想要的是,错误,BufferedWriter.