【发布时间】:2020-05-25 19:36:35
【问题描述】:
我已经编写了下面的构造函数,它从文件中获取一个单词,将它传递给一个返回单词翻译的外部方法“Translate”。
并行(以及对于我尚未完全编写的代码),构造函数将字符串单词作为它(一旦编写代码)将在字典中找到该单词。
但在此之前,我需要将单词和翻译都放入 ArrayList 中。我知道 Map 会更好,但我需要使用 ArrayList。
我的代码是这样做的,但有些地方我不明白。
我将单词写入数组列表然后翻译....所以我希望 ArrayList 是 Word1,Translation1,Word2,Translation2,
但是当我运行我的打印命令时,它会打印所有的单词,然后是所有的翻译......
我试图弄清楚这一点的原因是我希望能够对单词的数组列表进行排序(字典未排序),然后查找单个单词....并快速获取它的翻译
所以我的问题是 - 我是否正确使用了 ArrayList(在本练习中接受 ArrayList 的限制以及如何使用 word 作为键进行排序?
import java.io.FileNotFoundException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Scanner;
class Translate {
String original;
String translation;
public Translate(String original) throws FileNotFoundException {
this.original = original;
this.translation = translation;
ArrayList al = new ArrayList();
Path p1 = Paths.get("C:/Users/Green/documents/dictionary.txt");
Scanner sc = new Scanner(p1.toFile()).useDelimiter("\\s*-\\s*");
while (sc.hasNext()) {
String word = (sc.next());
String translation = (Translate(word));
al.add(word);
al.add(translation);
System.out.println("Print Arraylist using for loop");
for(int i=0; i < al.size(); i++) {
System.out.println( al.get(i));
}
}
}
public static void main(String args[]) throws FileNotFoundException {
Translate gcd = new Translate("envolope");
}
}
【问题讨论】:
-
你为什么不尝试联系字符串和翻译并将它们存储在同一个索引中?
-
您应该将单词和翻译组合在一个条目中。可能是具有两个字段的自定义类,或者是一个 Pair,甚至是一个
String[2]。否则你必须非常小心,不要弄乱顺序。 -
谢谢你,但鉴于我有两个数组列表条目,我该怎么做:al.add(word); al.add(翻译);
-
没有两个数组列表条目,只有一个:
al.add(new String[]{ word, translation });oral.add(Pair.of(word, translation));oral.add(new WordWithTranslation(word, translation));
标签: java