我试图阅读一个文本文件,以便我可以按名称查找一本书,然后输出其属性,即可获得奇怪的结果。帮助
这是代码:
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();
}
这是文件:
candy mang | doodle | 4586 | 45.0 |
摇篮|迈克尔| 1111 | 1.0 |
这是输出:
按1添加书籍,按2查找书籍。
2
您希望如何搜索这本书?
1
输入图书名称:candy mang
C
一
名词
d
1
ë
|
退出?
C
答案 0 :(得分:1)
看起来您正在尝试读取管道(|)作为分隔符的CSV文件。为什么不使用像以下的CSV库: http://opencsv.sourceforge.net/
然后您可以使用以下方式设置分隔符:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), '|');
然后,您可以逐行阅读文件,搜索您想要的图书:
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
}
}
答案 1 :(得分:0)
|
用作交流发电机(OR)。因此,使用"|"
拆分与使用""
拆分相同,这意味着拆分每个字符。这就是你有多个字符输出的原因。将特殊符号转义为"\\|"
观察:
不要像使用==
那样使用bookNames[j] == this.name
比较两个对象。而是使用bookNames[j].equals(this.name);