2013-04-11 89 views
0

我爲一項任務做了一個簡單的Java CLI程序,現在我試圖將它變成Android應用程序以獲得樂趣/體驗。 然而,它不工作...這是一個翻譯應用程序,當我在字典中輸入一個我知道的詞時,它仍然給我我的信息,如果用戶輸入了一個無效的單詞,我會投入。 我相信發生了什麼事情是因爲Eclipse的LogCat在運行時給我提供了以下消息:「無法打開文件進行讀取」,因此它無法正確讀取字典文件。簡單的Android翻譯應用程序無法正常工作

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); 
} 

任何幫助將不勝感激。

回答

1

您的文本文件位於何處?我猜想問題可能是它沒有下/ RES保存/生在你的項目文件夾中,之後就可以像使用一個InputStream:

 InputStream is = this.getResources().openRawResource(
      R.raw.textfilename); 
    try{ 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
     while(blah){ 
      do stuff 
     } 
    } 
    catch(Exception e){ 
     handle errors 
    } 
+1

爲什麼你把一個文本文件中的'/ RES/drawable' ? – Squonk

+0

好吧,保留原始資產或資產。這只是一個快速的解決方案,給它的想法。我會編輯答案。 –

+0

嗯,我可以繼續使用掃描儀嗎?它需要成爲我的程序的其餘工作的掃描儀。感謝你的回答! – dacelbot

相關問題