我正在尝试制作一个简单的扫描仪阅读器,从存储在C:UsersjamesDesktopprojectfiles的txt文件中读取,它被称为data "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+")
你的函数也不会编译,因为它没有任何返回值。