【问题标题】:Search ArrayList for keywords and return location在 ArrayList 中搜索关键字并返回位置
【发布时间】:2018-09-19 02:43:20
【问题描述】:

我正在尝试编写一种方法来搜索特定单词的 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;
        }
    }
}

【问题讨论】:

标签: java search arraylist


【解决方案1】:

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

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

但是ws 是一个Word 对象,除非你重写equals() 方法,否则它永远不会等于String 对象。您需要执行以下操作:

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

这是假设您为wor 创建了一个get 方法。

【讨论】:

    【解决方案2】:

    除了 GBlodgett 的回答,Word 类中的 number 是静态的,因此每个 Word 实例将具有相同的编号,您需要使用非静态变量来存储位置

    static class Words{
        private String wor;
        private static int number = -1;
        private int location;
    
        public Words(String wor) {
            this.wor = wor;
            number++;
            location = number;
        }
        public int getLocation() {
            return location;
        }
    
        public String toString() {
         return wor;
       }
    }
    

    【讨论】:

      【解决方案3】:

      你的代码应该是这样的:

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

      ws 是 Words 类的对象,你得把它改成 toString()

      【讨论】:

        【解决方案4】:

        你应该做的是 ws.equals(search) 你需要添加 ws.toString().equals(search) 当你从 toString()
        Words 类中的方法。 所以代码应该是这样的,

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-04-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-09-17
          • 1970-01-01
          • 1970-01-01
          • 2023-04-09
          相关资源
          最近更新 更多