这是我的代码:
public static void main(String[] args) throws IOException {
writeToFile ("c:\\scores.txt");
processFile("c:\\scores.txt");
}
public static void writeToFile (String filename) throws IOException {
BufferedWriter outputWriter = new BufferedWriter(new FileWriter(filename));
Scanner reader = new Scanner (System.in);
int Num;
System.out.println ("Please enter 7 scores");
for (int i = 0; i < 7; i++) {
Num= reader.nextInt ();
outputWriter.write(Num);
if(i!=6) {
outputWriter.newLine();
}
}
outputWriter.flush();
outputWriter.close();
}
public static void processFile (String filename) throws IOException, FileNotFoundException
{
double sum=0.00;
double number;
double average;
int count = 0;
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream(filename)));
String line;
while((line = inputReader.readLine()) != null)
{
number= Double.parseDouble(line);
System.out.println(number);
count ++;
sum += (number);
System.out.print ("Total Sum: ");
System.out.println(sum);
System.out.print("Average of Scores: ");
average=sum/count;
System.out.println(average);
}
inputReader.close();
}
这就是我的输出。
Please enter 7 scores
2
3
5
6
8
9
1
Exception in thread "main" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1011)
at java.lang.Double.parseDouble(Double.java:540)
at writefile.Writefile.processFile(Writefile.java:52)
at writefile.Writefile.main(Writefile.java:19)
Java Result: 1
我不知道如何解决这个问题。我不知道如何fiz浮动十进制或空字符串错误。文件中有奇怪的符号,没有整数。我该如何解决?请具体,因为我只是Java的初学者。
答案 0 :(得分:2)
outputWriter.write(1);
并不代表outputWriter.write("1");
您需要将outputWriter.write(Num);
更改为outputWriter.write(""+Num);
请参阅outputstream.write(int)
答案 1 :(得分:1)
发生错误是因为line
在某个时刻是一个空字符串,在解析字符串之前对此进行测试:
while ((line = inputReader.readLine()) != null) {
if (line.trim().length() > 0) {
number = Double.parseDouble(line);
// rest of loop
}
}
即,假设该行仅包含数字。如果还有其他字符,则必须在解析该行之前执行更仔细的验证。
答案 2 :(得分:1)
文件中有奇怪的符号,没有整数。
写一个字符。
所以它不会写你发送给它的int
值,而是它的字符表示。
如果您只是将数值写为String
然后将其检索为String
并解析它,那会更好。在writeToFile
方法中,修改此部分
for (int i = 0; i < 7; i++) {
Num = reader.nextInt ();
outputWriter.write(Integer.toString(Num));
if(i!=6) {
outputWriter.newLine();
}
}