I am having trouble reading from a simple text file and cannot seem to figure out why. I have done this before, and I am unsure as to what the issue is. Any help would be appreciated!
import java.io.File;
import java.util.Scanner;
public class CS2110TokenReader {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
File theFile = new File("data1.txt");
Scanner scnFile = new Scanner(theFile);
try {
scnFile = new Scanner(theFile);
} catch (Exception e) {
System.exit(1);
}
while (theFile.hasNext()) {
String s1 = theFile.next();
Double d1 = theFile.nextDouble();
System.out.println(s1 + " " + d1);
}
}
}
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method hasNext() is undefined for the type File
The method next() is undefined for the type File
The method nextDouble() is undefined for the type File
at CS2110TokenReader.main(CS2110TokenReader.java:20)
It will not even scan for the next line. That is my objective. To scan and read.
You are invoking the method of
Scannerclass onFilereference. ReplacetheFilewithscnFilein all the invocation.Secondly, you are invoking
next()andnextDouble(), but are only checking forhasNext()once. That may throw youNoSuchElementExceptionat some point of time. Make sure that, you have an input to read, before you actually read it.