当我从 TextView 中解析一个空字符串时,如果我已经设置了条件,则它会显示“unknown int””。代码如下。
else if (naqaBoolean) {
int i;
int durasiHaidh = 24;
int tempohSebenar = 0;
for (i = 1; i < 17; i++){
TextView tvStatus = findViewById(getResources().getIdentifier("status" + i, "id", MainActivity.this.getPackageName()));
TextView tvTempoh = findViewById(getResources().getIdentifier("tempoh" + i, "id", MainActivity.this.getPackageName()));
TextView tvMenstruasi = findViewById(getResources().getIdentifier("menstruasi" + i, "id", MainActivity.this.getPackageName()));
int hariIni = 0;
String text = (String.valueOf(tvTempoh.getText()));
if(text == "Seharian"){
hariIni = 24;
} else if (text == "-"){
hariIni = 0;
} else if (text == ""){
hariIni = 0;
} else {
hariIni = Integer.parseInt((String) tvTempoh.getText());
}
tempohSebenar = tempohSebenar + hariIni;
}
Toast.makeText(getApplicationContext(), tempohSebenar, Toast.LENGTH_SHORT).show();
}
最佳答案
一开始你使用:
String text = (String.valueOf(tvTempoh.getText()));
并使用您的 if
进行测试。
然后,在 else
block 中,将 (String) tvTempoh.getText());
解析为 int
。
相反,您应该使用 Integet.parseInt(text);
此外,字符串比较不应使用 ==
进行,而应使用 .equals
进行,因为 ==
是引用比较。如果字符串被缓存,有时它会起作用,但你不能确定。
这是因为 String.valueOf()
与强制转换 ((String)
) 不同。
关于java - 将空字符串解析为int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56254734/