java - 在 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;
}
}
}
解决方案
在您的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
.
推荐阅读
- flutter - 如何在单击按钮时使用 flutter_webview 返回上一页?
- python - 使用 numba @jit 加速我使用队列的多处理循环
- mapbox-gl-js - 根据经度和纬度获取查询RenderedFeatures的Mapbox点
- python - 从参数或同一类初始化 Python 类
- here-api - 具有自由格式输入 Geocoder API 的 Geogode 街道交叉口
- php - if/else 在 php 的 foreach 循环中不起作用
- clojure - Clojure:合并 2 个地图向量
- javascript - 将图像缓冲区发送到 node.js tcp 服务器
- python - 如何计算字符串中至少出现一次的单词数?
- c++ - 用 std::swap 交换二维数组中的行。它是如何工作的?