如何让我的程序跳过java中的一段文本?

时间:2017-01-11 06:38:04

标签: java text java.util.scanner nosuchelementexception

所以目前我正在运行以下代码来从一个名为Races.txt

的文件中读取
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编码项目之一,我意识到这可能是一个简单的修复,但任何额外的帮助将不胜感激

P.S。我意识到其余的代码在这一点上是不完整的,但我正在测试它以确保扫描程序能够工作,这样我就可以创建另一个我一直在研究的对象。谢谢!

2 个答案:

答案 0 :(得分:0)

这不是阅读此文件的完美方式。无论如何请检查以下代码是否适合您。

 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.nextLine();
                reader.skip("str:");
                reader.useDelimiter(";");
                str = reader.nextInt();
                reader.nextLine();
                reader.skip("dex:");
                dex = reader.nextInt();
                reader.nextLine();
                reader.skip("con:");
                con = reader.nextInt();
                reader.nextLine();
                reader.skip("intl:");
                intl = reader.nextInt();
                reader.nextLine();
                reader.skip("wis:");
                wis = reader.nextInt();
                System.out.println(str + wis + dex + con + intl + cha + maxAge + baseSpeed + name + size + description);
            }else if(reader.hasNext("Subrace:")){

            }
        }
        reader.close();
    }

由于你是一个新手,请尝试阅读你自己的正则表达式模式匹配,以避免扫描仪的这种跳过(模式)。

您可以将文件读入字符串,也可以逐行读取或使用分隔符读取。然后应用你的逻辑。而不是得到你的逻辑如何wrtten。这是超级刚性的,一个单一的空白或换行会搞砸了。

例如,您可以逐行阅读并对手头的字符串进行操作,而不是使用扫描仪本身。

public static void readRaceFile(String filename) throws FileNotFoundException{

             Scanner reader = new Scanner(new File(filename));
             System.out.println("File found");
             while(reader.hasNext()){
                 String line = reader.nextLine();

                 //Do you work with the 'line' string as you wish.. Split the string 
                 //or applying regex anything you want to get the details in the string. 

                 //System.out.println(reader.nextLine());
             }
}

答案 1 :(得分:0)

您应该使用完整的解析器,以便它可以处理更复杂的情况。最好是,如果您能够更改文件格式,则可以使用现有的解析器(例如JSON)。但是,如果您真的想要使用扫描仪,我已经概述了一种适用于您的样本数据集的方法。请注意,当您需要在数据值中包含分隔符时,此方法将会崩溃。

private static final String DELIMITER = "("
+ "\r\n|[\n\r\u2028\u2029\u0085]" // end of line
+ "|;" // semi-colons
+ "|," // commas
+ "|(?<=:)" // match after colon
+ "|(?=\\{|\\})|(?<=\\{|\\})" // match before+after brace
+ ")+"; // one or more

public static void readRaceFile(String filename) throws FileNotFoundException{
    try(Scanner reader = new Scanner(new File(filename))) {
        reader.useDelimiter(DELIMITER);
        while(reader.hasNext()){
            String s = reader.next();
            if(s.equals("{")) {
                System.out.println("{start block}");
            } else if(s.equals("}")) {
                System.out.println("{end block}");
            } else if(s.endsWith(":")) {
                s = s.substring(0, s.length()-1);
                System.out.println("attribute: " + s);
            } else {
                s = s.trim();
                System.out.println("\tvalue: " + s);
            }
        }
    }
}

<强>输出:

attribute: Race
    value: name
{start block}
attribute: str
    value: 0
attribute: dex
    value: 0
attribute: con
    value: 0
attribute: intl
    value: 0
attribute: wis
    value: 0
attribute: cha
    value: 0
attribute: max age
    value: 100
attribute: base speed
    value: 35
attribute: size
    value: medium
attribute: description
    value: This is a race
attribute: abilities
    value: Darkvision - You can see in dim light up to 60 feet as if it were bright light
    value: Idiosy - You are stupid
attribute: number of possible tool proficiency choices
    value: 0
attribute: possible tool proficiencies
    value: brewer's tools
    value: masonry tools
attribute: number of possible skill proficiency choices
    value: 0
attribute: possible skill proficiencies
    value: perception
attribute: number of possible language choices
    value: 0
attribute: possible language choices
    value: elvish
    value: dwarf
attribute: given tool proficiencies
    value: martial weapons
attribute: given skill proficiencies
attribute: given languages
    value: english
attribute: cantrips
    value: 1
    value: fireball
    value: 3
    value: plant growth
{end block}