首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何让我的程序跳过java中的一段文本?

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

Stack Overflow用户
提问于 2017-01-11 14:38:04
回答 2查看 603关注 0票数 0

因此,目前我正在运行以下代码,以便从名为Races.txt的文件中读取数据

代码语言:javascript
复制
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");
        }
    }
}

该代码是从下面的文本文件中读取的,该文本文件的格式如下所示:

代码语言:javascript
复制
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:”或"{\nstr:“跳过"str:”时,我收到以下错误:

代码语言:javascript
复制
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编码项目之一,我意识到这可能是一个简单的修复,但任何其他帮助都将不胜感激

附注:我意识到代码的其余部分在这一点上是不完整的,但我正在测试它,以确保扫描器可以工作,这样我就可以创建另一个我一直在处理的对象。谢谢!

EN

回答 2

Stack Overflow用户

发布于 2017-01-11 17:15:32

这不是阅读此file.Anyway的完美方法请检查以下代码是否适合您。

代码语言:javascript
复制
 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();
    }

由于你是一个新手,请尝试自己阅读有关regex模式匹配的内容,以避免Scanner的这种跳过(模式)。

您可以将文件读入字符串,也可以逐行读取或使用分隔符。然后应用你的逻辑。而不是从逻辑上理解你是如何写的。这是非常死板的,一个空格或换行符就会把事情搞砸。

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

代码语言:javascript
复制
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());
             }
}
票数 0
EN

Stack Overflow用户

发布于 2017-01-11 17:16:45

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

代码语言:javascript
复制
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);
            }
        }
    }
}

输出:

代码语言:javascript
复制
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}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41584256

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档