比较和检索 ArrayList 中的元素 [英] Compare and retrieve elements from ArrayList

查看:23
本文介绍了比较和检索 ArrayList 中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个简单的字典,将字符串与 ArrayList 上的单词进行比较,然后从列表中返回不同的值.ArrayList 用外来词布局,然后是英文等价物,所以我的想法是我输入一个词,使用扫描仪将其与数组列表进行比较,然后返回索引值 +1 所以如果我输入的单词是列表中的第 7 个,我希望它返回第 8 个单词并将其打印出来.

I'm trying to build a simple dictionary that compares a string to a word on the ArrayList and then returns a different value from the list. The ArrayList is laid out with the foreign word and then followed by the English equivalent so the idea is that I type in a word, use scanner to compare it to the array list and then return the index value +1 so if the word I type is 7th on the list, I want it to return the 8th word and print it out.

我已经有了输入字符串并进行比较的基本思想,但我不知道如何从 ArrayList 返回以下单词:

I've got the basic idea of inputting a string and comparing it, but I don't know how to return the following word from the ArrayList:

public void translateWords(){
        String nameSearch;
        nameSearch=input.nextLine();

        for (Phrase c:phrases) {
            if (c.getName().equals(nameSearch))  {
                System.out.println( c.advancedToString());      
                return;
            }
        }
        System.out.println("not on list");

我已经尝试使用 ArrayList 的 get 方法,但我不确定如何使用它,因此这里非常感谢任何反馈.

I've tried playing about with the get method for the ArrayList but I'm unsure on how to use it so any feedback would be very appreciated here.

推荐答案

for-each 在这种情况下不合适,因为您无法访问连续元素,在您的情况下翻译单词.所以我建议你使用 Iterate

for-each is not appropriate in this case because you can not access successive elements, in your case translated words. So I suggest you to use Iterate

我想 phrases 的类型是 List

public void translateWords(){
        String nameSearch;
        nameSearch=input.nextLine();

        Iterator<Phrase> it = phrases.iterator();
        while(it.hasNext())
        {
           Phrase c = it.next();
           if (c.getName().equals(nameSearch))  {
                System.out.println( it.next().advancedToString());      
                return;
            }
        }

        System.out.println("not on list");
}

这篇关于比较和检索 ArrayList 中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆