問題描述
嘗試從 EditText 獲取雙精度值并在將它們傳遞給另一個(gè) Intent 之前對(duì)其進(jìn)行操作.不使用原始數(shù)據(jù)類型,所以我可以使用 toString 方法.
Trying to get double values from an EditText and manipulate them before passing them to another Intent. Not using primitive data type so I can use toString methods.
問題是當(dāng)我包含 protein=Double.valueOf(p).doubleValue();樣式命令,程序強(qiáng)制立即關(guān)閉,而不會(huì)在 logcat 中留下任何信息.如果我將它們注釋掉并設(shè)置一些虛擬數(shù)據(jù),例如 protein = 1.0;它沒有問題.原始數(shù)據(jù)類型和解析雙精度也會(huì)發(fā)生同樣的情況.此代碼與普通 java 中的虛擬數(shù)據(jù)完美配合.我做錯(cuò)了什么?
Problem is when I include the protein=Double.valueOf(p).doubleValue(); style commands, the program force closes immediately without leaving any info in the logcat.If I comment them out and set some dummy data like protein = 1.0; it works with no problems. Same happens with primitive data types and parse double. This code works perfectly with dummy data in normal java. What am I doing wrong?
EditText txtProt, txtCarb, txtFat, txtFiber, txtPoints;
String p, c, f, fi;
Double protein, carbs, fat, fiber;
double temp;
Integer points;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v("Create Prompt", "ready for layout");
setContentView(R.layout.main);
Log.v("Layout Created", "ready for variable assignment");
txtProt = (EditText) findViewById(R.id.Protein);
txtCarb = (EditText) findViewById(R.id.Carbs);
txtFat = (EditText) findViewById(R.id.Fat);
txtFiber = (EditText) findViewById(R.id.Fiber);
txtPoints = (EditText) findViewById(R.id.Points);
btnCalc = (Button) findViewById(R.id.Calc);
Log.v("Variables Assigned", "ready for double assignment");
p = txtProt.getText().toString();
c = txtCarb.getText().toString();
f = txtFat.getText().toString();
fi = txtFiber.getText().toString();
protein=Double.valueOf(p).doubleValue();
carbs=Double.valueOf(c).doubleValue();
fat=Double.valueOf(f).doubleValue();
fiber=Double.valueOf(fi).doubleValue();
Log.v("Doubles parsed", "ready for calculations");
//these are the problem statements
protein = 1.0;
carbs = 1.0;
fat = 1.0;
fiber = 1.0;
protein *= 16;
carbs *= 19;
fat *= 45;
fiber *= 14;
temp = protein + carbs + fat - fiber;
temp = temp/175;
points = new Integer((int) temp);
推薦答案
我會(huì)這樣做:
try {
txtProt = (EditText) findViewById(R.id.Protein); // Same
p = txtProt.getText().toString(); // Same
protein = Double.parseDouble(p); // Make use of autoboxing. It's also easier to read.
} catch (NumberFormatException e) {
// p did not contain a valid double
}
程序強(qiáng)制立即關(guān)閉,而不會(huì)在 logcat 中留下任何信息"
"the program force closes immediately without leaving any info in the logcat"
我不知道是否不會(huì)在 logcat 輸出中留下信息,但強(qiáng)制關(guān)閉通常意味著存在未捕獲的異常 - 例如 NumberFormatException.
I don't know bout not leaving information in the logcat output, but a force-close generally means there's an uncaught exception - like a NumberFormatException.
這篇關(guān)于在Android中將字符串轉(zhuǎn)換為雙精度的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!