我的代码是关于如果用户输入pH值(正常pH值= 7.35-7.45)它会给他答案是酸性pH值还是碱性pH值或正常,那么我想保存一个名为phStatus的字符串作为在onclick方法之后,在resultTextView中最后调用其他字符串的答案,这里是:
Button resultButton = (Button) findViewById ( R.id.resultButton );
final TextView resultTextView = (TextView) findViewById ( R.id.resultTextView );
resultButton.setOnClickListener ( new OnClickListener ( ) {
@Override
public void onClick ( View v )
{
EditText phET = (EditText) findViewById ( R.id.phEditText );
int phEntered = Integer.parseInt ( phET.getText ( ).toString ( ) );
String phStatus = "";
if ( phEntered < 7.35 )
{phStatus = "Acidosis";}
else if ( phEntered > 7.45 )
{phStatus = "Alkalosis";}
else
{phStatus = "Normal acid-base balance";}
String resultMSG = "This is " + phStatus;
resultTextView.setText ( resultMSG );
}
答案 0 :(得分:2)
试试这个......
添加try catch块来处理异常。
Button resultButton = (Button) findViewById ( R.id.resultButton );
final TextView resultTextView = (TextView) findViewById ( R.id.resultTextView );
resultButton.setOnClickListener ( new OnClickListener ( ) {
@Override
public void onClick ( View v ) {
// TODO Auto-generated method stub
EditText phET = (EditText) findViewById ( R.id.phEditText );
try{
double phEntered = Double.parseDouble ( phET.getText ( ).toString ( ) );
String phStatus = "";
if ( phEntered < 7.35 ) {
phStatus = "Acidosis";
}else if ( phEntered > 7.45 ) {
phStatus = "Alkalosis";
}else {
phStatus = "Normal acid-base balance";
}
String resultMSG = "This is " + phStatus;
resultTextView.setText ( resultMSG );
Toast.makeText ( getApplicationContext ( ), "Not Long Enough :(", 1000 ).show ( );
}catch(Exception e){
// exception handle here
}
}
答案 1 :(得分:1)
将int与double进行比较是有效的 - 它会将int提升为a 在进行比较之前加倍。 您只需要@deepak提到的试试捕获.. 您也可以尝试为EditText指定一个默认字符串(可能是“0”)。
答案 2 :(得分:0)
我在你们的帮助下想出来了,非常感谢,现在这是代码:
公共类ABG扩展了Activity { @覆盖 protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.abg);
}
String phStatus;
@Override
public String ph ( String phStatus )
{
EditText phET = (EditText) findViewById ( R.id.phEditText );
try
{
double phEntered = Double.parseDouble ( phET.getText ( ).toString ( ) );
if ( phEntered < 7.35 )
{
phStatus = "Acidosis";
}
else if ( phEntered > 7.45 )
{
phStatus = "Alkalosis";
}
else
{
phStatus = "Normal acid-base balance";
}
}
catch (Exception e)
{
// exception handle here
}
return phStatus;
}
@Override
public void result ( View v )
{
// TODO Auto-generated method stub
String resultMSG = "This is " + ph ( phStatus );
TextView resultTextView = (TextView) findViewById ( R.id.resultTextView );
resultTextView.setText ( resultMSG );
}
}