分析文本文件中的数字时出现Android无效Int错误



我的网站中有一个.txt文件,其中包含一个数字(在本例中为3),我使用此代码来检查这个数字是否大于或小于另一个数字,但代码给了我这个错误:

03-03 16:27:43.734: E/AndroidRuntime(16318): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.downloadingprogressbar/com.example.downloadingprogressbar.MainActivity}: java.lang.NumberFormatException: Invalid int: "3

这是我的代码:

HttpGet httppost = new HttpGet("http://mywebsite.org/version.txt");
    HttpResponse response;
    try {
        response = httpclient.execute(httppost);
        HttpEntity ht = response.getEntity();
        BufferedHttpEntity buf = new BufferedHttpEntity(ht);
        InputStream is = buf.getContent();

        BufferedReader r = new BufferedReader(new InputStreamReader(is));
        StringBuilder total = new StringBuilder();
        String line;
        while ((line = r.readLine()) != null) {
            total.append(line + "n");
        }
        String casa = new String(total.toString());
        //boolean version = (casa>4);
        if (Integer.parseInt(casa)>4){
            risposta.setText("la tua versione è aggiornata");
        }
        else {
            risposta.setText("aggiorna la tua versione");
        }

我同意Kon的观点,您的变量"casa"包含其他字符。

尝试使用trim()方法:

 if (Integer.parseInt(casa.trim())>4){
...
...
...

但现在我看到你在total变量中添加了"\n",这"新行"有必要吗?:

 while ((line = r.readLine()) != null) {
            total.append(line);
        }

尝试删除数字周围的所有空白:

if (Integer.parseInt(casa.trim()) > 4){
    // ...
}

最新更新