简体   繁体   English

如何在 arraylist (Java) 中搜索对象的元素,如果存在,则打印该对象的 .toString

[英]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.在我尝试创建的这个特定程序中,我希望用户能够创建一个具有不同元素(字符串、整数、布尔值)的新对象,然后将其存储在 ArrayList 中,类似于大多数 Book/Library 项目。 To do that I have created a class called Game where I created a constructor, setters/getters as well as a .toString method.为此,我创建了一个名为 Game 的类,我在其中创建了一个构造函数、setter/getter 以及一个 .toString 方法。 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.在 mainmenu 类中,我还创建了一些 switch 语句,为用户提供基于他们想要做什么的不同选择。 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这是我要求用户为他们想要存储的新游戏提供字段的地方,正如我所指出的,我忘了提到我已经创建了一个名为 storage 的 ArrayList

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之后我希望用户能够通过提供标题来搜索这个 arrayList 并找到具有相同标题的游戏的所有可用信息

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.我知道我的 gameSearch 功能不起作用,但这是我所能得到的。

I'm going to assume that storage is the name given to the list of Game objects.我将假设storageGame对象列表的名称。 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.如果是这种情况, storage.equals()将无法工作,因为您希望列表中的特定对象等于 search_title,而不是整个列表。 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:放入 Map 而不是添加到列表中:

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

Then just search the Map by the key:然后只需通过键搜索 Map :

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 :而您正在寻找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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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