This is my method for checking if the first three elements are the same
carModel is a string
purchasePrice is a double
purchaseDate is a Date
I stored these in a txt file, separating with a comma and a space like ", "
However, this method always returns false,even if i input just the same record. But when I changed the first"&&" into "||", it would return 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]
and s[2]
are String
s, so comparing them to double
or to Date
will never return true.
You'll have to parse the input Strings into the correct type before making the comparison.
You'll need something like this (I didn't fix the Date
comparison, since I don't know how you represent the date in your input file):
if ((s[0].equals(c.carModel)) &&(Double.parseDouble(s[1])==c.purchasePrice)&& (s[2].equals(c.purchaseDate))
&& (s[5].equals("false")) ){
return true;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments