所以目前我正在下面的代碼從一個名爲Races.txt如何讓我的程序跳過java中的一段文本?
import java.util.Scanner;
import java.io.*;
public class FileReader {
public FileReader(){
}
public static void readRaceFile(String filename) throws FileNotFoundException{
Scanner reader = new Scanner(new File(filename));
System.out.println("File found");
int str = 0, dex = 0, con = 0, intl = 0, wis = 0, cha = 0, maxAge = 0, baseSpeed = 0;
String name = "", size = "", description = "";
while(reader.hasNext()){
if(reader.hasNext("Race:")){
reader.skip("Race:");
reader.useDelimiter("\\{");
name = reader.next();
reader.skip("\nstr:");
reader.useDelimiter(";");
str = reader.nextInt();
reader.skip(";\ndex:");
dex = reader.nextInt();
reader.skip(";\ncon:");
con = reader.nextInt();
reader.skip(";\nintl:");
intl = reader.nextInt();
reader.skip(";\nwis:");
wis = reader.nextInt();
System.out.println(str + wis + dex + con + intl + cha + maxAge + baseSpeed + name + size + description);
}else if(reader.hasNext("Subrace:")){
}
}
reader.close();
}
public static void main(String args[]){
try{
readRaceFile("Races.txt");
}catch(IOException e){
System.out.println("file not found");
}
}
}
文件的代碼是從一個格式相同的方式,下面的文本文件閱讀,閱讀如下所示:
Race:name{
str:0;
dex:0;
con:0;
intl:0;
wis:0;
cha:0;
max age:100;
base speed:35;
size:medium;
description:This is a race;
abilities:Darkvision - You can see in dim light up to 60 feet as if it were bright light, Idiosy - You are stupid;
number of possible tool proficiency choices:0;
possible tool proficiencies:brewer's tools, masonry tools;
number of possible skill proficiency choices:0;
possible skill proficiencies:perception;
number of possible language choices:0;
possible language choices:elvish, dwarf;
given tool proficiencies:martial weapons;
given skill proficiencies:;
given languages:english;
cantrips:
1, fireball
3, plant growth;
}
當我運行程序時,我可以成功跳過「Race:」並導入「name」並打印它,如果我想,但是當我試圖通過使用「\ nstr:」,「str:」跳過「str: 「或」{\ nstr:「我收到以下錯誤:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.skip(Unknown Source)
at java.util.Scanner.skip(Unknown Source)
at FileReader.readRaceFile(FileReader.java:18)
at FileReader.main(FileReader.java:39)
這是我的第一個Java編碼項目之一,我意識到這可能是一個簡單的修復,但更多的幫助,將不勝感激
附:我意識到其他代碼在這一點上是不完整的,但是我正在測試它以確保掃描儀能夠工作,以便我可以創建另一個我一直在研究的對象。謝謝!
這只是我的意見,但考慮到數據的(合理的)複雜性,我建議你在看看XML或JSON數據結構,而不是,它具有定義良好且經過測試的API可用,它將使您的生活從長遠來看變得如此簡單 – MadProgrammer
是的,如果您可以更改數據格式,則應該使用XML或JSON,並且我會推薦使用JAXB等映射技術MOXy作爲實現)用於XML或用於JSON的Jackson – kwisatz