Reputation: 37
I am writing a program (according to a specification) that reads a file and uses it to create a simulation of robots in a warehouse. I have used a scanner to read the file and a switch statement to perform the right actions, but only certain cases are being executed.
Here is the code I am having trouble with:
private static void readFromFile() {
Scanner input = null;
float capacity = 0;
float chargeSpeed = 0;
try {
input = new Scanner(
new File("C:\\Users\\User\\Documents\\Uni\\Java Projects\\Kiva\\configs\\twoRobots.sim"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (input.hasNextLine()) {
String line = input.nextLine();
String[] arr = line.split("\\s+"); //regex for whitespace
switch (arr[0]) {
case "format":
System.out.println(arr[0]);
break;
case "width":
System.out.println(arr[0]);
break;
case "height":
System.out.println(arr[0]);
break;
case "capacity":
System.out.println(arr[0]);
break;
case "chargeSpeed":
System.out.println(arr[0]);
break;
case "podRobot":
System.out.println(arr[0]);
break;
case "shelf":
System.out.println(arr[0]);
break;
case "station":
System.out.println(arr[0]);
break;
case "order":
System.out.println(arr[0]);
break;
}
line = input.nextLine();
}
And here is the file (tworobots.sim):
format 1
width 4
height 4
capacity 50
chargeSpeed 1
podRobot c0 r0 3 1
podRobot c1 r1 3 3
shelf ss0 2 2
station ps0 0 2
order 13 ss0
And here is the output (all the actions should be listed):
format
height
chargeSpeed
podRobot
station
order
Why is this? Any help would be much appreciated.
Upvotes: 0
Views: 70
Reputation: 489
The extra line is present in the end.
line = input.nextLine(); // Remove this line in the end.
Upvotes: 1
Reputation: 1685
The problem is in this excerpt:
while (input.hasNextLine()) {
String line = input.nextLine();
String[] arr = line.split("\\s+"); //regex for whitespace
switch (arr[0]) {
//...
}
line = input.nextLine(); // You read the next line and do nothing with it.
}
All the lines are read, but that extra nextLine
call is reading the next line, then doing nothing with it as you immediately read the line after at the start of the loop again. Just remove that second call to fix it.
Upvotes: 1