扫描文本文件时如何跳过前导字符串



我正在制作一个程序,该程序使用文本文件中的指令绘制基本图像。指令的格式为:

SIZE 1000 500
// GROUND
LINE 0 350 1000 350
LINE 0 351 1000 351
LINE 0 352 1000 352
LINE 0 353 1000 353

这是我的代码:

public void start(Stage stage) {
int fwidth = 0;
int fheight = 0;
try {
Scanner obj = new Scanner(new File("scene.txt"));
while(obj.hasNextLine()){
String str = obj.nextLine();
if(str.contains("SIZE")){
String a = "SIZE";
obj.skip(a);
System.out.println('b');
fwidth = obj.nextInt();
fheight = obj.nextInt();
}
if(str.contains("LINE")){
obj.skip("LINE");
System.out.println('a');
}
}

这给出了一个NoSuchElementException。我想这是因为fwidth和fheight将前导字符串作为int,但我不知道如何让扫描仪从一开始跳过字符串,一旦知道它是什么类型的指令,就只读取数字

几个建议:

首先,我不认为

Scanner.skip()

做你想做的事。.skip((方法的目的是告诉扫描仪";跳过";行,而不是跳过当前所在的行。这将在下次调用.nextLine((.时完成

我会完全删除你对.skip((的所有调用。此外,这更像是一种偏好,但我会使用switch语句,而不是多个if。它使您的代码可读性更强。

其次,正如Johnny在评论中提到的那样,使用.split((可能会更好,因为根据我的经验,.nextInt((会产生意想不到的结果。所以,你的代码应该是这样的:

while(obj.hasNextLine()){
String[] strArray = obj.nextLine().split(" ");
switch(strArray[0]){
case "SIZE":
fwidth = Integer.parseInt(strArray[1]);
fheight = Integer.parseInt(strArray[2]);
break;
case "LINE":
//do nothing
break;
}
}

您可以更轻松地完成以下操作:

String str = obj.nextLine();
String[] arr = str.split("\s+");// Split on whitespace
if("SIZE".equals(arr[0])) {
fwidth = Integer.parseInt(arr[1]);
fheight = Integer.parseInt(arr[2]);
} else if("LINE".equals(arr[0])) {
//...
}

如注释中所述,您可以使用obj.next()逐行扫描,而不是使用nextLine():

Scanner obj = new Scanner(new File("scene.txt"));
int fwidth, fheight;
int num1, num2, num3, num4;
while(obj.hasNextLine() && obj.hasNext()){
String str = obj.next();
if(str.contains("SIZE")){
String a = "SIZE";
fwidth = obj.nextInt();
fheight = obj.nextInt();
System.out.println("fwidth : " + fwidth + ", fheight : " + fheight);
} else if(str.contains("LINE")){
num1 = obj.nextInt();
num2 = obj.nextInt();
num3 = obj.nextInt();
num4 = obj.nextInt();
System.out.println("num1 : " + num1 + ", num2 : " + num2 + ", num3: " + num3 + ", num4: " + num4);
}
}

我用你提供的文件测试了这个,它似乎有效:

src : $ java ScannerLeading 
b
fwidth : 1000, fheight : 500
num1 : 0, num2 : 350, num3: 1000, num4: 350
num1 : 0, num2 : 351, num3: 1000, num4: 351
num1 : 0, num2 : 352, num3: 1000, num4: 352
num1 : 0, num2 : 353, num3: 1000, num4: 353

最新更新