【问题标题】:Extraction of string and integer from txt从txt中提取字符串和整数
【发布时间】:2021-04-22 01:29:49
【问题描述】:

我正在尝试制作一个简单的扫描仪阅读器来读取存储在 C:\Users\james\Desktop\project\files\ 中的 txt,它被称为数据“data.txt”,问题是存储的信息是这样的:

ASSETS    21
CHOROY 12
SHELL      9

所以你可以看到字符串和我想要提取的整数之间的空格是随机的。我试图做到这一点:

public data(String s) //s is the name of the txt "data.txt"
{
    if (!s.equalsIgnoreCase("Null"))
    {
        try {
            File text = new File(s); 
            Scanner fileReader = new Scanner(text);
            while (fileReader.hasNextLine()) 
            { 
                String data = fileReader.nextLine();
                String[] dataArray = data.split(" ");
                String word = dataArray[0]; 
                String number = dataArray[1]; 
                int score = Integer.parseInt(number);
                addWord(word, score);
            }
            fileReader.close();
        } 
        catch (FileNotFoundException e) 
        {
            System.out.println("File not found");
            e.printStackTrace();
        }
        System.out.println("Reading complete");
    }

但是拆分只是在字符串和整数之间有一个空格,所以我想知道如何提取在同一行中用任意数量的空格分隔的两件事。示例:

Line readed: HOUSE 1 -> String word = "HOUSE"; int score = "1";
Line readed: O          5 -> String word = "O"; int score = "5";

【问题讨论】:

  • 但是拆分只是在字符串和整数之间有一个空格,所以我想知道如何提取两个用任意数量的空格分隔的东西行。 - 将 data.split(" ") 替换为 data.split("\\s+")

标签: java file java.util.scanner reader txt


【解决方案1】:

而不是data.split(" ")

你可以使用

data.split("\\s+")

你的函数也不会编译,因为它没有任何返回。

【讨论】:

    猜你喜欢
    • 2020-07-20
    • 1970-01-01
    • 2013-07-03
    • 2013-01-10
    • 2022-10-16
    • 2019-09-14
    • 1970-01-01
    相关资源
    最近更新 更多