我可以请你指导我如何解决这个问题吗? 我需要将inputWord与.txt文件中的字符串进行比较,如果找到,则返回整行但如果没有,则显示“找不到单词”。
示例:
inputWord: abacus
Text file content:
abaca - n. large herbaceous Asian plant of the banana family.
aback - adv. archaic towards or situated to the rear.
abacus - n. a frame with rows of wires or grooves along which beads are slid, used for calculating.
...
so on
Returns: abacus with its definition
我想要做的是将我的inputWord与“ - ”(连字符作为分隔符)之前的单词进行比较,如果它们不匹配,则移动到下一行。如果匹配,则复制整行。
我希望它看起来不像我要求“做我的功课”但我尝试了不同论坛和网站的教程。我也读过java文档,但我真的不能把它们放在一起来实现这个目标。
提前谢谢!
更新:
这是我目前的代码:
if(enhancedStem.startsWith("a"))
{
InputStream inputStream = getResources().openRawResource(R.raw.definitiona);
try {
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String s = in.readLine();
String delimiter = " - ";
String del[];
while(s != null)
{
s = in.readLine();
del = s.split(delimiter);
if (enhancedStem.equals(del[0]))
{
in.close();
databaseOutput.setText(s);
break;
}
}
in.close();
}
catch (FileNotFoundException e) {
databaseOutput.setText("" + e);
}
catch (IOException e1) {
databaseOutput.setText("" + e1);
}
}
非常感谢!这是我提出的,它正确地返回输入的定义,但问题是,当我输入文本文件中找不到的单词时,应用程序崩溃。口号似乎不起作用。知道我怎么能陷阱吗? Logcat在第4342行说NullPointerExcepetion,这是
s = in.readLine();
答案 0 :(得分:2)
假设文本文件中每行的格式是统一的。这可以通过以下方式完成:
1)逐行读取文件。
2)根据分隔符拆分每一行,并在临时字符串数组中收集拆分的字符串标记。
3)临时令牌数组中的第一个条目是“ - ”符号前面的单词。
4)将临时数组中的第一个条目与搜索字符串进行比较,如果匹配则返回整行。
以下代码可以放在一个函数中来实现:
String delimiter = "-";
String[] temp;
String searchString = "abacus";
BufferedReader in = new BufferedReader(new FileReader(file));
while (in.readLine() != null) {
String s = in.readLine();
temp = s.split(delimiter);
if(searchString.equals(temp[0])) {
in.close();
return s;
}
}
in.close();
return ("Word not found");
希望这有帮助。
答案 1 :(得分:0)
myreader = new BufferedReader(new FileReader(file));
String text = "MyInput Word";
while(!((text.equals(reader.readLine())).equals("0")));