我想做一個應用程序拆分人民之間的法案,但每當我試圖在代碼中分兩個數字,它總是給我0.0。爲什麼是這樣?每當我分開我得到0.0
下面是代碼:
public class MainActivity extends Activity {
public int x = 0;
public double y = 1.00;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Button
Button btn = (Button) findViewById(R.id.button);
//EditText
EditText nop = (EditText) findViewById(R.id.editText);
EditText cob = (EditText) findViewById(R.id.editText2);
try{
x = Integer.valueOf(nop.getText().toString());
} catch (NumberFormatException e) {
x = 0;
}
try{
y = Double.valueOf(cob.getText().toString());
} catch (NumberFormatException e) {
y = 1.00;
}
//TextView
final TextView tv = (TextView) findViewById(R.id.textView);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Double z = (y/x);
tv.setText("You will each pay:" + (z));
}
});
}
}
也許你的'Integer.valueOf'方法拋出一個異常。那麼你總是有0.0 – MrT
@mrT當你除以零時,你不會得到0.0。你會得到'NaN'或'Infinity'。 –
在catch語句中分配'x = 0'有點危險,因爲這可能導致被零除,這將返回一個零除異常。 – HyperZ