1

I am not sure why I am receiving this error and what's the fix to it in the following snippet of code:

        String srcFile=args[0];
        Scanner fileIn = new Scanner(srcFile);
        //    if (fileIn.isFile() && fileIn.canRead())

        CarDB carDatabase = new CarDB();
        while(fileIn.hasNext())
        {       
          String[] line = fileIn.nextLine().split(",");
          double mpg = Double.parseDouble(line[0]);
          int cylinders = Integer.parseInt(line[1]);
          int power = Integer.parseInt(line[2]);
          int year = Integer.parseInt(line[3]);
          int region = Integer.parseInt(line[4]);
          String makerName = line[5].trim();
          String carName = line[6].trim();

          carDatabase.addCar(makerName, carName, mpg, cylinders, power, year, region);// add car
          carDatabase.addMaker(makerName);//add maker to list

        } 

and line 36 is : double mpg = Double.parseDouble(line[0]);

Error is:

java CarDBMain cars.txt 
java.lang.NumberFormatException: For input string: "cars.txt"
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1250)
    at java.lang.Double.parseDouble(Double.java:540)
    at CarDBMain.main(CarDBMain.java:36)
0

1 Answer 1

3

You are having this Scanner fileIn = new Scanner("cars.txt"); so your first line will be "cars.txt"

 Scanner fileIn = new Scanner(new File(srcFile));//Or probably path of file

Here create file and pass the commandline argument,means file path,to File constructor and pass that file to Scanner.

You are passing file name as String to Scanner.

Constructors

Scanner(File source)<---Takes File you want to read
Scanner(String source)<----Takes String you want to read
etc.
Sign up to request clarification or add additional context in comments.

4 Comments

Well, this is a project in which I believe we are not supposed to change that specific line. Can we incorporate this any other way?
well, isn't the file name a string?
But it will take that String as input while you want to pass file from which you are reading.
It worked for me. Thanks. Will be accepting the answer in 6 minutes :) Apparently it was a typo or possibly they wanted us to catch it somehow!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.