我正在为我的高中软件项目制作一个类似于应用程序的抽认卡。我可以通过将单词和它们各自的翻译写入文件来存储它们,但我想知道是否有可能将它们读入二维数组。
我可以用逗号或其他字符将它们分开吗?
此外,是否有一种方法可以将单词及其各自的翻译联系起来。例如,如果我调用单词“x”,是否有函数可以调用单词“translated x”(如果它在数组中)?
谢谢堆!!
让我们把问题分解一下。
word
和 atranslation
word
和存储translation
在数据结构中(@Glen Pierce 关于使用地图的建议是一个很好的建议)假设我们的文件是这样的,我们使用逗号分隔单词和翻译(这也是我的西班牙语词汇量的范围):
hello,hola
good,bueno
现在一些代码,让我们将文件读入地图。
// a map of word to translation
Map<String, String> wordMap = new HashMap<String, String>();
// a class that can read a file (we wrap the file reader in a buffered reader because it's more efficient to read a file in chunks larger than a single character)
BufferedReader fileReader = new BufferedReader(new FileReader("my-file.txt"));
// a line from the file
String line;
// read lines until we read a line that is null (i.e. no more lines)
while((line = fileReader.getLine()) != null) {
// split the line, returns an array of parts
String[] parts = line.split(",");
// store the parts in meaningful variables
String word = parts[0];
String translation = parts[1];
// now, store the word and the translation in the word map
wordMap.put(word, translation);
}
// close the reader (note: you should do this with a try/finally block so that if you throw an exception, you still close the reader)
fileReader.close();
所以现在我们有一个地图,其中包含文件中的所有单词和翻译。给定一个词,您可以像这样检索翻译:
String word = "hello";
String translation = wordMap.get(word);
System.out.println(word + " translates to " + translation);
输出:
hello translates to hola
我想下一步是让用户给你一个词,让你返回正确的翻译。我会把它留给你。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句