Reputation:
I am having trouble reading the first word of a text file. If the first word equals 'Circle' I want to create a new Circle object in my array.
FileInputStream fileIn = new FileInputStream("shapeFile.txt");
Scanner scan = new Scanner(fileIn);
while(scan.hasNextLine()) {
String shape = scan.next();
if(shape.equals("Circle")) {
myShapes.addShape(new Circle(scan.nextInt(), scan.nextInt(), scan.nextInt(), Color.RED));
}
}
I am getting the following error for the above code, pointing to the line String shape = scan.next();
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at shapes.ShapeManagement.main(ShapeManagement.java:151)
Java Result: 1
If anyone could help me resolve this I would be most grateful.
Upvotes: 3
Views: 3494
Reputation: 12972
The reason your likely getting this exception is because scan.hasNextLine()
can return true
even if there are no tokens on that line. If you call scan.next()
when there are no tokens after the marker, you will get the java.util.NoSuchElementException
you are seeing.
So, swap out scan.hasNextLine()
for scan.hasNext()
.
Alternatively you could swap out scan.next()
for scan.nextLine()
and then check whether the first word in that line was the one you are looking for. This could potentially be faster for files with large numbers of lines.
I hope this helps.
Link to the Scanner API for reference.
Upvotes: 4
Reputation: 300
You may want to modify the code as follows:
FileInputStream fileIn = new FileInputStream("shapeFile.txt");
Scanner scan = new Scanner(fileIn);
int[] var1 = new int[3];
while(scan.hasNext()) {
String shape = scan.next();
if(shape.equals("Circle")) {
for(int i = 0; i < 3;i++) {
if(scan.hasNextInt()) {
var1[i] = scan.nextInt();
} else {
break;
}
}
myShapes.addShape(new Circle(var1[0], var1[1], var1[2], Color.RED));
}
}
Upvotes: 0