我的应用程序有两个文本视图(TV1和TV2)和一个按钮。当您点击TV2中的按钮显示随机数时。我想要TV1中的TV2值中随机数的总和,依此类推。但它失败了,应用程序关闭了,你能告诉我我做错了什么吗?谢谢
这是我的代码:
public class MainActivity extends Activity {
Button b1;
TextView tv1, tv2;
Random myRandom;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(R.id.tv1);
b1 = (Button) findViewById(R.id.b1);
tv2=(TextView)findViewById(R.id.tv2);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void a(View view){
String result = "";
myRandom = new Random();
for (int i = 0; i < 1; i++) {
result += String.valueOf(myRandom.nextInt(100)) + "\n";
}
tv2.setText("Lo vendiste por: " + result);
String x=tv1.getText().toString();
String y=tv2.getText().toString();
int nro1=Integer.parseInt(x);
int nro2=Integer.parseInt(y);
int sumar = nro1+nro2;
String resultado=String.valueOf(sumar);
tv1.setText(resultado);
}
}
答案 0 :(得分:0)
您正在尝试将单词解析为整数:
tv2.setText("Lo vendiste por: " + result);
String x=tv1.getText().toString();
String y=tv2.getText().toString();
int nro1=Integer.parseInt(x);
int nro2=Integer.parseInt(y);
所以String x是Lo vendiste por:&#34;随机数&#34;并且你想将它解析成一个int,这是不可能的
应该是这样的:
tv2.setText(result);
String x=tv1.getText().toString();
String y=tv2.getText().toString();
int nro1=Integer.parseInt(x);
int nro2=Integer.parseInt(y);
您也可以尝试拆分字符串:
tv2.setText("Lo vendiste por: " + result);
String x=tv1.getText().toString();
String y=tv2.getText().toString();
String[] splittedString = x.split(" ");
int nro1=Integer.parseInt(splittedString[2]);
int nro2=Integer.parseInt(y);
我无法证明这是否正常,我没有尝试过代码,但是为了分割字符串here也是一个样本