从txt中提取字符串和整数
Extraction of string and integer from txt
我正在尝试制作一个简单的扫描仪 reader 来读取存储在 C:\Users\james\Desktop\project\files\ 中的 txt,它被称为数据“data.txt”,问题是存储的信息是这样的:
ASSETS 21
CHOROY 12
SHELL 9
正如您所见,字符串和我想要提取的整数之间的 space 是随机的。我试着做这个:
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");
}
但是字符串和整数之间的拆分只有一个空 space 所以我想知道如何提取用任意数量的 space 分隔的两个东西在同一行。示例:
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+")
您的函数也不会编译,因为它没有任何 return.
我正在尝试制作一个简单的扫描仪 reader 来读取存储在 C:\Users\james\Desktop\project\files\ 中的 txt,它被称为数据“data.txt”,问题是存储的信息是这样的:
ASSETS 21
CHOROY 12
SHELL 9
正如您所见,字符串和我想要提取的整数之间的 space 是随机的。我试着做这个:
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");
}
但是字符串和整数之间的拆分只有一个空 space 所以我想知道如何提取用任意数量的 space 分隔的两个东西在同一行。示例:
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+")
您的函数也不会编译,因为它没有任何 return.