问题
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.
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");
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.
回答1:
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
I suppose phrases
is of type List<Phrase>
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");
}
回答2:
Would something like this do the job for you? Not tested, just from my head:
public void translateWords(){
String nameSearch;
nameSearch=input.nextLine();
if(c.indexof(nameSearch)){
System.out.println(c.get(c.indexof(c.indexof(nameSearch)+1));
} else {
System.out.println("not on list");
}
}
回答3:
Another way would be to use a dictionary, e.g., a Java HashMap. Without knowing how your Phrase
class is implemented, this might look like this:
// create dictionary
Map<Phrase, Phrase> d = new HashMap<Phrase, Phrase>();
// add phrases
d.put(new Phrase("Guten Tag", "de"), new Phrase("Good morning", "en"));
// get translation
Phrase p = d.get(new Phrase(nameSearch, "de"));
(To make this work, Phrase.equals
and Phrase.hashCode
have to be implemented.)
This seems to be a better choice of data structure for your task. Using a HashMap, lookup times for items are O(1), as opposed to O(n) in your approach, which could be relevant if your dictionary contains thousands or millions of phrases, or if you have to do this very often. A possible downside is that the entries have to be really equal, e.g. you could not (easily) check for "similar" phrases or words.
来源:https://stackoverflow.com/questions/19904569/compare-and-retrieve-elements-from-arraylist