【发布时间】:2012-01-29 06:15:05
【问题描述】:
我需要使用分隔符“:”解析一个文本文件
文本文件如下所示:
a : 29173 : He : James : 474937 : 2 : 4 : 1
t : 27184 : 她 : Susan: 474930 : 6 : 4 : 2
c : 28174 : He : Meg : 474931 : 5 : 4 : 1
p : 29190 : 她 : Robin : 474947 : 4 : 4 : 4
我的第一个问题是如何/可以解析第一个字符以在 switch 语句中使用? 我在想类似下面的代码(我把它放在一起......但我很确定这是不正确的)。
我知道我可以读取第一个字符,并且我知道我可以使用带有字符的 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)
【问题讨论】:
-
如果你知道什么不工作更容易帮助:) 编译错误?
标签: java parsing if-statement switch-statement