[英]Trying to read from text file using string.split
I'm trying to read through a text file so that i can find a book by name and then output its attributes, im getting wierd results. 我正在尝试通读一个文本文件,以便我可以按名称查找一本书,然后输出其属性,而结果却很奇怪。 help?
救命?
This is the code: 这是代码:
System.out.print( "Enter name of book: " );
input2 = scanner.nextLine();
this.setName(input2);
String bookName = getInfo.readLine();
int i = 0, num = 0;
while(bookName != null)
{
String[] bookNames = bookName.split("|");
i++;
for(int j = (i*4-4); j<(i*4); j++)
{
if (bookNames[j] == this.name){
num = 1;
}
}
if(num == 1){
System.out.println(bookName);
num = 0;
}
bookName = getInfo.readLine();
}
This is the file : 这是文件:
candy mang|doodle|4586|45.0| 糖果man |涂鸦| 4586 | 45.0 |
cradle|Michael|1111|1.0| 摇篮|迈克尔| 1111 | 1.0 |
This is the output: 这是输出:
Press 1 to add a book, and 2 to find a book. 按1添加一本书,然后按2查找一本书。
2 2
How would you like to search for the book? 您想如何搜索这本书?
1 1个
Enter name of book: candy mang 输入书名:糖果man
c C
a 一种
n ñ
d d
l 升
e Ë
| |
Exit? 出口?
c C
It looks like your trying to read a CSV file where a pipe (|) is the delimiter. 似乎您尝试读取以竖线(|)为分隔符的CSV文件。 Why not just use a CSV library like: http://opencsv.sourceforge.net/
为什么不只使用CSV库,例如: http : //opencsv.sourceforge.net/
You can then set the delimiter using: 然后,您可以使用以下命令设置定界符:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), '|');
You can then read the file line by line searching for your desired book: 然后,您可以逐行搜索所需的书来阅读文件:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), '|');
String [] nextLine;
while ((nextLine = reader.readNext()) != null)
{
// nextLine[] is an array of values from the line
if(nextLine[0] == desiredBookName)
{
// Output desired attributes
}
}
|
is a special character in regex. 是正则表达式中的特殊字符。 So you will need to escape it.
因此,您将需要对其进行转义。
String[] bookNames = bookName.split("\\|"); // Not the 2 backslashes.
|
in regular expression is used as an alternator(OR). 在正则表达式中用作交流发电机(OR)。 So splitting with
"|"
所以用
"|"
分割 is same as splitting with ""
which means split each character. 与用
""
分割相同,表示分割每个字符。 That's the reason you have multiple character output. 这就是输出多个字符的原因。 Escape the special symbol as
"\\\\|"
将特殊符号转义为
"\\\\|"
Observation : 观察:
Do not compare two objects using ==
as you have done bookNames[j] == this.name
. 完成
bookNames[j] == this.name
请勿使用==
比较两个对象。 Instead use bookNames[j].equals(this.name);
而是使用
bookNames[j].equals(this.name);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.