我需要使用分隔符“:”
来解析文本文件文本文件如下所示:
a:29173:他:雅各书:474937:2:4:1
t:27184:她:苏珊:474930:6:4:2
c:28174:他:梅格:474931:5:4:129190:她:罗宾:474947:4:4:4
我的第一个问题是如何解析第一个在switch语句中使用的字符? 我在想类似下面的代码(我把它放在一起......但我很确定是不正确的)。
我知道我可以阅读第一个字符&我知道我可以使用带有char(s)的switch语句,但我仍然坚持如何将两者放在一起。
File file = new File("test.txt");
// Read the file
try {
Scanner scanner = new Scanner(file).useDelimiter(":");
String line = scanner.nextLine();
while (scanner.hasNextLine())
{
line = line.trim();
int index;
String type;
String name;
String identifier = scanner.next();
switch(line.charAt(0)) {
case 'p':
index = scanner.nextInt();
name = scanner.next();
break;
case 'c':
index = scanner.nextInt();
type = scanner.next();
name = scanner.next();
int partyC = scanner.nextInt();
int empathyC = scanner.nextInt();
int carryingCapacityC = scanner.nextInt();
break;
case 't':
index = scanner.nextInt();
type = scanner.next();
int creatureT = scanner.nextInt();
int weightT = scanner.nextInt();
int valueT = scanner.nextInt();
break;
case 'a':
index = scanner.nextInt();
type = scanner.next();
int creatureA = scanner.nextInt();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
VS
好吧,所以我已经阅读并玩了一些,并认为我可以使用if-else循环。但是,我收到了一些错误(在代码之下)。
File file = new File("test.txt");
// Read the file
try {
Scanner scanner = new Scanner(file).useDelimiter(":");
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
line = line.trim();
int index;
String type;
String name;
char identifier = line.charAt(0);
if (identifier == 'p') {
index = scanner.nextInt();
name = scanner.next();
} else if (identifier == 'c') {
index = scanner.nextInt();
type = scanner.next();
name = scanner.next();
int partyC = scanner.nextInt();
int empathyC = scanner.nextInt();
int carryingCapacityC = scanner.nextInt();
} else if (identifier == 't') {
index = scanner.nextInt();
type = scanner.next();
int creatureT = scanner.nextInt();
int weightT = scanner.nextInt();
int valueT = scanner.nextInt();
} else if (identifier == 'a') {
index = scanner.nextInt();
type = scanner.next();
int creatureA = scanner.nextInt();
} else {
System.out.println("This is not a valid line of input");
} System.out.println("Identifier: " + identifier);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
错误:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at SorcerersCave.main(SorcerersCave.java:33)
答案 0 :(得分:1)
我认为你可以逐行阅读文件。获取第一个char切换如下:
switch(line.charAt(0)) {
case 'a':
//...
case 'p':
//...
//...
}
而不是使用分隔符并执行.next()
,而是使用String[] parts = line.split(":")
来提供字符串数组。并修剪每个元素,并使用Integer.parseInt(parts[index].trim())
。
此外,您不需要while (scanner.hasNext())
。而是做
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
//split
//switch