这是我检查前三个元素是否相同的方法
carModel 是一个字符串
购买价格是双倍
purchaseDate 是一个日期
我将它们存储在一个txt文件中,用逗号和空格分隔,例如“,”
但是,即使我输入相同的记录,此方法也始终返回 false。但是当我将第一个“&&”更改为“||”时,它会返回true。
public static boolean exist(Car c) {
String line = "";
File file = new File("Car Records.txt");
try {
BufferedReader fr = new BufferedReader(new FileReader(file));
while ((line = fr.readLine()) != null) {
String[] s = line.split(", ");
if ((s[0].equals(c.carModel)) &&(s[1].equals(c.purchasePrice))&& (s[2].equals(c.purchaseDate))
&& (s[5].equals(false)) ){
return true;
}
}
fr.close();
} catch (IOException e) {
System.out.println("Error reading file");
}
return false;
}
最佳答案
s[0]
、s[1]
和 s[2]
是 String
,因此将它们与 double
或 Date
进行比较将永远不会返回 true。
在进行比较之前,您必须将输入字符串解析为正确的类型。
您需要这样的东西(我没有修复Date
比较,因为我不知道您如何在输入文件中表示日期):
if ((s[0].equals(c.carModel)) &&(Double.parseDouble(s[1])==c.purchasePrice)&& (s[2].equals(c.purchaseDate))
&& (s[5].equals("false")) ){
return true;
}
关于java - 将测试文件中的现有字符串与带有参数的新输入者对象进行比较时,始终返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41074892/