简体   繁体   中英

How to search an element of an object in an arraylist (Java) and if it exists, print the .toString of that object

In this particular program that I am trying to create I want the user to be able to create a new object with different elements (string, int, boolean), and then store it in an ArrayList, similar to most Book/Library projects. To do that I have created a class called Game where I created a constructor, setters/getters as well as a .toString method. In the mainmenu class, I have also created some switch statements to provide the user with different choices based on what they want to do. Here is where I request the user to provide the fields for the new game that they want to store as pointed out I forgot to mention that I have created an ArrayList named storage

ArrayList <Game> storage = new ArrayList <Game> ();
private void gameInsert() 
    {
        String title;
        String desc;
        int date;
        String quality;
        Boolean given;  //(similar to the ones created in the game class)

        for (int index = 0; index < 1; index++) 
        {
        System.out.println("Please enter a title: ");
        title = keyboard.nextLine().toLowerCase();
        System.out.println("Please enter the genre: ");
        desc = keyboard.nextLine();
        System.out.println("Please enter the year of release: ");
        date = Integer.parseInt(keyboard.nextLine());
        System.out.println("Please enter the quality of the product");
        System.out.println("NC = new condition, MC= Mint condition, BC = Barely Used , U = Used ");
        quality = keyboard.nextLine().toUpperCase();
        System.out.println("Is the item borrwed to someone? ");
        System.out.println("Press 1 = Yes | Press 2 = No");
        if ( Integer.parseInt(keyboard.nextLine()) == 1) 
        {
            given = true;
        }
        else
            given = false;
        volume ++;
        storage.add(new Game(title, desc, date, quality, given ));
        } 

After that I wanted the user to be able to search through this arrayList by providing a title and find all the available information for the game that has the same title

private void gameSearch() 
    {

        System.out.println("Enter the game's title!: ");
        String search_title = keyboard.nextLine().toLowerCase();
        for (int i= 0; i <storage.size(); i++) 
        if(storage.equals(search_title)) 
        {
            System.out.println("The game was found!");
            // print the .toString for this particular object;
            // or print by using the getters of the game class.
           // example given: title: ----
           //                genre: ---- etc.
        }
        else 
        {
            System.out.println("I am sorry, game not found. Please try again.");
        } 

I know that my gameSearch function does not work but that is as far as I was able to get.

I'm going to assume that storage is the name given to the list of Game objects. If that's the case, storage.equals() couldn't work since you want a particular object in the list to equal search_title, not the whole list. You can accomplish what you want by doing this:

for (Game game:storage) {
  if game.getTitle().equals(search_title) {
    System.out.println("The game was found!");
  }
}

However, if I were you I wouldn't use a list at all. I would use a Map instead. Create a Map instead of a list:

Map<String, Game> storage = new HashMap<>();

Put into the Map instead of adding into the list:

storage.put(title, new Game(title, desc, date, quality, given ));

Then just search the Map by the key:

Game found = storage.get(title);
private void gameSearch() {
        boolean foundGame = false;
        System.out.println("Enter the game's title!: ");
        String search_title = keyboard.nextLine().toLowerCase();
        for (int i = 0; i < storage.size(); i++) {
            Storage storage = storage.get(i);
            if (storage.getTitle().equalsIgnoreCase(search_title)) {
                System.out.println("The game was found!");
                // print the .toString for this particular object;
                // or print by using the getters of the game class.
                // example given: title: ----
                // genre: ---- etc.
                foundGame = true;
                break;
            }
        }
        if(!foundGame){
            System.out.println("I am sorry, game not found. Please try again.");
        }
    }

Let's say you have this list of games:

List<Game> storage = List.of(
    new Game("My game title 1", "short description", 2019, "U", false),
    new Game("My game title 2", "short description", 2019, "U", false),
    new Game("My game title 3", "short description", 2019, "U", false),
    new Game("My game title 4", "short description", 2019, "U", false)
);

And you are looking for My game title 3 :

String searchTitle = "My game title 3";

You search function is:

String result = storage.stream()
    .filter(game -> game.getTitle().equalsIgnoreCase(searchTitle))
    .map(Object::toString)
    .findFirst()
    .orElse("I am sorry, game not found. Please try again.");
System.out.println(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM