首页 > 解决方案 > 在 ArrayList 中搜索关键字并返回位置

问题描述

我正在尝试编写一种方法来搜索特定单词的 ArrayList,然后打印该单词所有出现的位置。

这就是我所拥有的,它可以正常工作,直到我输入要搜索的单词,但它什么也没打印:

import java.util.ArrayList; 
import java.util.Scanner;

public class W7E2 {
    public static void main(String[]args) {
        System.out.println("Please anter words: ");
        Scanner sc = new Scanner(System.in);
        String []w = sc.nextLine().split(" ");

        ArrayList<Words> word = new ArrayList<Words>();
        for(int i=0; i<w.length; i++) {
            word.add(new Words(w[i]));
        }
        System.out.println(word);

        System.out.println("Please enter the word you want to search: ");
        String search = sc.nextLine();


        for(Words ws: word) {
            if(ws.equals(search)) {
                System.out.println(ws.getLocation());
            }
        }

    }

    static class Words{
        private String wor;
        private static int number = -1;

        public Words(String wor) {
            this.wor = wor;
            number++;
        }
        public int getLocation() {
            return number;
        }

        public String toString() {
            return wor;
        }
    }
}

标签: javasearcharraylist

解决方案


在您的if声明中查看是否ArrayList包含您拥有的单词:

if(ws.equals(search)) {
    System.out.println(ws.getLocation());
}

Butws是一个Word对象,除非您覆盖该equals()方法,否则它永远不会等于该String对象。您需要执行以下操作:

if(ws.getwor().equals(search)) {
        System.out.println(ws.getLocation());
}

这是假设您为wor.


推荐阅读