你好,我正在创建一个游戏,它有分数,我需要使用 setText 添加和更改分数。
我在转换时遇到问题,因为我在字符串中获取文本值并对其求和时出现错误。
TextView pvoce = (TextView) findViewById(R.id.pvoce);
TextView papp = (TextView) findViewById(R.id.papp);
if (escolhaApp == "pedra" && escolhaUsuario == "tesoura" || escolhaApp == "papel" && escolhaUsuario == "pedra" || escolhaApp == "tesoura" && escolhaUsuario == "papel") {
textoResultado.setText(" You Lose ");
String soma = 1;
int totalapp = (soma + papp);
String totalappString = Integer.toString(totalapp);
papp.setText(totalappString);
} else if (escolhaUsuario == "pedra" && escolhaApp == "tesoura" || escolhaUsuario == "papel" && escolhaApp == "pedra" || escolhaUsuario == "tesoura" && escolhaApp == "papel") {
textoResultado.setText(" You Win ");
int soma = 1;
int totalvoce = soma + pvoce;
String totalvoceString = Integer.toString(totalvoce);
pvoce.setText(totalvoceString);
}
错误:类型不兼容:无法将 int 转换为 String 错误:不兼容的类型:String 无法转换为 int 错误:二元运算符“+”的错误操作数类型 第一种类型:int 第二种:TextView
最佳答案
Java 是一种静态类型语言,这意味着您不能将值分配给不兼容的类型(String soma = 1;
不是有效的分配)。此外,papp
是 TextView
的实例,而不是 int
,因此您不能执行 int totalapp = (soma + papp);
.
在将其添加到任何其他值之前,您必须将 TextView
文本强制转换为 int
,例如:
TextView papp = (TextView) findViewById(R.id.papp);
int soma = 1;
int pappInt = 0;
try {
pappInt = Integer.parseInt(papp.getText().toString());
} catch (NumberFormatException nfe) {
// Cannot parse papp.getText() as an Integer
}
int totalapp = (soma + pappInt);
关于java - 添加值并插入 setText,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58366064/