如何解决从txt中提取字符串和整数
我正在尝试制作一个简单的扫描仪阅读器来读取存储在 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+")
此外,您的函数也无法编译,因为它没有任何返回值。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。