Meaningless Drivel is fun!*
The moose likes Beginning Java and the fly likes Java scanner Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Java scanner" Watch "Java scanner" New topic
Author

Java scanner

cole relm
Greenhorn

Joined: Sep 16, 2011
Posts: 3
I keep getting this error when trying to run my program: Exception in thread "main" java.util.InputMismatchException and I know it's because of my scanner. I have tried messing around with the scanner for a couple hours now and I can't find the solution....so I come to the internet to hopefully get help with this. My code consists of three classes but I suspect the problem is in one of the classes which does all of the scanning and retrieving of information from a .csv file.

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39478
    
  28
You get an InputMismatchException (IME) whenever a Scanner cannot convert the String it has to its return value. For example, if myScanner.nextInt() encounters text like "123.45", it will throw an IME.
Two likely causes:
1: Your keyboard input isn't in the correct format
Try putting the reading inside a loop like this, though it would be better to write a utility class and do all your reading via that utility class.
2: You are reading a blank end of line
That problem only occurs when you use the nextLine() method; the documentation tells you what nextLine() does, but it doesn't warn you that nextLine() doesn't do what you think it does. Look at this old post which describes that problem.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39478
    
  28
Why are you using \n as a delimiter? You should check what the default delimiter is, and also what line end on Windows® is. You will find that using \n might lead to errors on Windows files (or old Mac files).

Have you really been told to start identifiers with _? That is not regarded as correct style in Java™ (except for package names in special circumstances.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39478
    
  28
And welcome to the Ranch
cole relm
Greenhorn

Joined: Sep 16, 2011
Posts: 3
Thanks for the reply. I found out what the problem was and am seeking some advice as to how I should go about fixing this. The following snippet is the cause of the problem:



The file from which I'm scanning from looks like this:
Mike,Smith,66.1,9
Aaron,Tike,90.4,10
Fred,Dotson,85.5,9


but after I added a comma at the end of every line, it worked. What do I need to do to in order to properly read my csv file without having to add additional commas?
 
jQuery in Action, 2nd edition
 
subject: Java scanner