gpt4 book ai didi

java - 当我尝试解析字符串时,我的应用程序崩溃了

转载 作者:行者123 更新时间:2023-12-01 23:28:20 25 4
gpt4 key购买 nike

我正在尝试解析一个字符串来计算我的产品总价格,但是当我使用“Integer.parseInt”时,我的应用程序崩溃了。 我知道我必须初始化一个字符串数组,导致指令“Integer.parseInt”无法解析 NULL,但我不知道问题到底是我的数组元素来自于分割字符串。请帮助我...我的代码:

    class Thread2 implements Runnable {//recieve
@Override
public void run() {
while (true) {
try {
final String message = input.readLine();
if (message != null) {
owner.runOnUiThread(new Runnable() {
@Override
public void run() {
String[] a = message.split("\\#");
int n = a.length;
for(int i=1;i<n;i++){

String[] b =a[i].split("\\*");

tee.append(b[0]+" "+b[1]+"\n");
y.append(b[1]+"*");

P1=Integer.parseInt(b[1]);

//total = total+p1[i];


}



te.setText(Integer.toString(total));



}
});
} else {
Thread myThred = new Thread(new Thread21());
myThred.start();
return;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

最佳答案

请使用try-catch来处理ui block 内的异常。

    try {
String[] b =a[i].split("\\*");

tee.append(b[0]+" "+b[1]+"\n");
y.append(b[1]+"*");

P1=Integer.parseInt(b[1]);

//total = total+p1[i];
} catch(Exception ex) {
}

除此之外,您还可以在 catch block 中使用 Exception 而不是 IOException 处理各种异常并避免崩溃。谢谢

编辑如下:

     } catch (Exception e) {
e.printStackTrace();
}

而不是:

     } catch (IOException e) {
e.printStackTrace();
}

关于java - 当我尝试解析字符串时,我的应用程序崩溃了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58299719/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com