我正在编写一个程序(根据规范),该程序读取文件并使用它来创建仓库中的机器人模拟。我使用扫描程序读取文件和switch语句来执行正确的操作,但只有某些情况正在执行。
以下是我遇到问题的代码:
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();
}
这是文件(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
这是输出(应列出所有操作):
format
height
chargeSpeed
podRobot
station
order
这是为什么?任何帮助将不胜感激。
答案 0 :(得分:1)
额外的行最后出现。
line = input.nextLine(); // Remove this line in the end.
答案 1 :(得分:1)
问题在于摘录:
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.
}
读取所有行,但是额外的nextLine
调用正在读取下一行,然后在循环开始之后立即读取该行时不执行任何操作。只需删除第二个电话来修复它。