“线程中的异常”主“java.lang.NumberFormatException:”后跟txt中的值

时间:2017-12-06 02:13:17

标签: java exception

所以我只是修复了一个错误,然后我得到了异常错误,不知道要修改什么来修复它。 我看过类似的问题,但似乎没有一个与我的具体问题有关。

import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;


public class AAAAAA {
    public static void main (String[] args)throws IOException {

    final String fileName = "classQuizzes.txt";
//1)
    Scanner sc = new Scanner(new File(fileName));

    //declarations 
    String input;
    double total = 0;
    double num = 0;
    double count = 0;
    double average = 0;
    String lastname;
    String firstname;
    double minimum;
    double max;


//2) process rows    
            while (sc.hasNextLine()) {
               input = sc.nextLine();
               System.out.println(input);



   //find total
               total += Double.parseDouble(input);  //compile error on using input
               count++; 

               System.out.println(count); //test delete later
   //find average (decimal 2 points)
               System.out.println("hi"); //test
               average = (double)total / count;
               System.out.println("Average = " + average);

//3) class statistics


            }

     }
}

1 个答案:

答案 0 :(得分:1)

它实际上是运行时异常,而不是编译错误。

原因是因为你的Scanner正在逐行读取整个文件,并且正在点击无法解析为double的内容。

// for each line in the file
while (sc.hasNextLine()) {
    String line = sc.nextLine();
    System.out.println(line);

    // split the line into pieces of data separated by the spaces
    String[] data = line.split();

    String firstName = null;
    String lastName = null;

    // get the name from data[]
    // if the array length is greater than or equal to 1
    // then it's safe to try to get something from the 1st index (0)
    if(data.length >= 1)
        firstName = data[0];
    if(data.length >= 2)
        lastName = data[1];

    // what is the meaning of the numbers?

    // get numbers
    Double d1 = null;
    if(data.length >= 3){
        try {
            d1 = Double.valueOf(data[2]);
        } catch (NumberFormatException e){
            // couldn't parse the 3rd piece of data into a double
        }
    }

    Double d2 = null;
    // do the same...

    // do something with 'firstName', 'lastName', and your numbers ...
}