Search code examples
javanumberformatexception

Parsing a number throws: Exception in thread "main" java.lang.NumberFormatException: For input string


I am making an object oriented program that takes an array of object type Date and writes it to a file. But I am having a problem parsing a number. I can't see where my int and String variables are being mixed up:

public static Date[] createMe() throws FileNotFoundException
{
   Scanner kb = new Scanner(System.in);
   System.out.print("please enter the name of the file: ");
   String fileName= kb.nextLine();
   Scanner fin = new Scanner(new File(fileName));
   int count = 0;
   while (fin.hasNextLine()){
      count++;
      fin.nextLine();
   }
   fin.close();
   Date[] temp = new Date[count];
   fin = new Scanner(fileName);
   while(fin.hasNextLine()){
      String line = fin.nextLine();
      String[] s = line.split("/");
      int month = Integer.parseInt(s[0]);
      int day = Integer.parseInt(s[1]);
      int year = Integer.parseInt(s[2]);
   }
   return temp;
}

I keep getting this error code and I don't know why:

please enter the name of the file: Track.java
Exception in thread "main" java.lang.NumberFormatException: For input string: "Track.java"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)
    at Date.createMe(Date.java:49)
    at DateTester.main(DateTester.java:28)

I should be only inputting my string with my Scanner kb right? So why am I getting this error?


Solution

  • problem is in this line:

    fin = new Scanner(fileName);
    

    you are creating a Scanner from a String filename. Which is the path to file that you type in. Not the file itself. you created fin Scanner correctly a few lines above that. Just do the same again.