Reputation: 64
I'm having issues reading a Float in from an external data file (.txt) I've read a number of different posts about this error, and common problems, and I still don't know what I'm doing wrong. The advice varies, some people say use ".nextLine()", some people say use ".next()", I've tried a bunch of these combinations and am still having problems.
Here's the relevant section:
public void read_file(Interface iface) throws FileNotFoundException {
int readCount = 0;
File file = new File(""); \\FILE PATH REDACTED
Scanner reader = new Scanner(file);
reader.useDelimiter(",|\\n");
while(reader.hasNext()){
String type = reader.next();
float rate = reader.nextFloat();
String desc = reader.next();
//Some irrelevant code follows
Text file:
Test1
10.00
Test2
I get the following exception:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextFloat(Scanner.java:2496)
at ReadFile.read_file(ReadFile.java:20)
at Main.main(Main.java:21)
I conducted a test and it definitely reads in the first line (I was able to print that). So I'm guessing its something to do with the line return at the end of the line after Test1. But I thought that would get handled by the use of the delimiter.
I'm using IntelliJ (some people have suggested that using a ,(comma) instead of a .(period) can sometimes resolve the error - but this seems limited to NetBeans or Eclipse, I forget).
Does anyone have any suggestions?
Upvotes: 0
Views: 196
Reputation: 26
I think the line breaks you set in 'reader.useDelimiter()' should be consistent with the line breaks in the file. Generally, it is '\r\n' for Windows, '\n' for Unix, and '\r' for Mac.I hope it can help you.
Upvotes: 1
Reputation: 392
Apparently, you must add this line before or after useDelimiter
:
reader.useLocale(Locale.US);
It's required for the scanner to be able to detect floats.
For whatever reason, once it started working, I tried removing the line and it kept working. I reverted back to your original script, and it was still working. I think the Locale settings are persistent or something.
Anyways, if adding this line works, I suggest leaving it like that :)
Upvotes: 1