[英]Every time I divide I get 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));
}
});
}
}
我的猜測是你沒有在點擊后評估這些值。 try / catch的代碼應該在onclick方法中。
單擊按鈕從EditText
獲取值,否則您將無法獲得輸入的值,因為獲取x
和y
值的代碼會在您啟動應用程序后立即執行,並且不再進行進一步提取。
做這個
final TextView tv = (TextView) findViewById(R.id.textView);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
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;
}
Double z = (y / x);
tv.setText("You will each pay:" + (z));
}
});
如果以下代碼中存在異常,則x將為零。
try {
x = Integer.valueOf(nop.getText().toString());
} catch (NumberFormatException e) {
x = 0;
}
現在因為例外,你除以零並且將得到Infinity而不是0.0
還要確保參與者的默認數量為1而不是零。 如果將其設置為零,則最好不要進行除法並強制用戶輸入正確的數字,或者必須將除數的異常捕獲為零。
public class MainActivity extends Activity {
public int x = 1;
public double y = 1.00;
public EditText nop;
public EditText cob;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Button
Button btn = (Button) findViewById(R.id.button);
//EditText
nop = (EditText) findViewById(R.id.editText);
cob = (EditText) findViewById(R.id.editText2);
//TextView
final TextView tv = (TextView) findViewById(R.id.textView);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try{
x = Integer.valueOf(nop.getText().toString());
} catch (NumberFormatException e) {
x = 1;
}
try{
y = Double.valueOf(cob.getText().toString());
} catch (NumberFormatException e) {
y = 1.00;
}
Double z = (y / x);
tv.setText("You will each pay:" + (z));
}
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.