我为一个作业制作了一个简单的 Java CLI 程序,现在我正试图将它变成一个 Android 应用程序以获得乐趣/体验。但是,它不起作用......它是一个翻译应用程序,当我输入一个我知道在字典中的单词时,如果用户输入无效单词,它仍然会给我我输入的信息。我相信发生的事情是它没有正确读取字典文件,因为 Eclipse 的 LogCat 在运行时给我以下消息:“无法打开文件进行读取。”
public class MainActivity extends Activity {
TreeMap<String, String> tree = new TreeMap<String, String>();
public final static String EXTRA_MESSAGE = "";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Scanner dictinput = null;
try{
getAssets().open("dict.txt");
dictinput = new Scanner(getAssets().open("dict.txt"));
}
catch (Exception e) {
System.err.println("Could not open file");
System.exit(-1);
}//Puts the dictionary in a stringbuffer
StringBuffer dict = new StringBuffer();
String[] arrtemp = new String[1600];
while(dictinput.hasNext()) {
dict.append(dictinput.nextLine());
dict.append("|");
}//Then puts it in a string so it can be split at the |'s using .split
String strstr = dict.toString();
arrtemp = strstr.split("\\|");
//puts the dictionary into a treemap
for(int i=0; i<arrtemp.length-1; i++) {
if(i==0)
tree.put(arrtemp[i].toLowerCase(), arrtemp[i+1]);
else {
i++;
tree.put(arrtemp[i].toLowerCase(), arrtemp[i+1]);
}
}
}
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.editmessage);//The only way I've found to get the text from the user.
String temp = editText.toString();
Scanner scan = new Scanner(temp);
String finalmessage = null;
while(scan.hasNext()){
String temp1 = scan.next();
if (tree.containsKey(temp1.toLowerCase()))
finalmessage = temp;
else
finalmessage = "No match found, try another word or phrase";
}
intent.putExtra(EXTRA_MESSAGE, finalmessage);
startActivity(intent);
}
任何帮助将不胜感激。