My code is supposed to perform a VERY BASIC search and print an ArrayList of books whose titles match those of a String parameter.
It works perfectly if I hardcode the parameter but for some reason it doesn't work if I save the use user input as a variable first... why does this change the output?
package com.formation;
public class Livre {
private int id;
private String title;
private int year;
private int edition;
public Livre(int id, String title, int year, int edition) {
super();
this.id = id;
this.title = title;
this.year = year;
this.edition = edition;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getEdition() {
return edition;
}
public void setEdition(int edition) {
this.edition = edition;
}
@Override
public String toString() {
return "Livre [id=" + id + ", title=" + title + ", year=" + year + ", edition=" + edition + "]";
}
}
**
package com.formation;
import java.util.ArrayList;
import java.util.List;
public class Google {
private List<Livre> Livres;
public Google(List<Livre> Bookbook) {
super();
this.Livres = Bookbook;
}
public List<Livre> search(String mot) {
List<Livre> searchResult = new ArrayList<Livre>();
for (Livre livre : this.Livres) {
if (livre.getTitle() == mot) {
searchResult.add(livre);
}
}
return searchResult;
}
}
*
package com.formation;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
List<Livre> books = new ArrayList<Livre>();
Livre livre1 = new Livre(1234, "TOTO", 1982, 4);
books.add(livre1);
Livre livre2 = new Livre(2345, "TATA", 1992, 2);
books.add(livre2);
Livre livre3 = new Livre(3456, "TUTU", 1962, 7);
books.add(livre3);
Livre livre4 = new Livre(4567, "TITI", 1972, 5);
books.add(livre4);
Livre livre5 = new Livre(5678, "TETE", 1952, 8);
books.add(livre5);
Google google = new Google(books);
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a title:");
String book = sc.nextLine();
System.out.println(google.search(book)); //returns []
System.out.println(google.search("TATA")); //returns [Livre [id=2345, title=TATA, year=1992, edition=2]]
}
}
livre.getTitle() == motis the culprit, look at How do I compare Strings in Java?. If you hardcode the parameter the same instance of the literal"TATA"will be used and thus it'll work while user input will result in an equal but different string instance. Uselivre.getTitle().equals(mot)instead.