在Android中将字符串转换为Double

Pro*_*mie 22 string double android android-edittext

尝试从EditText获取double值并在将它们传递给另一个Intent之前对其进行操作.不使用原始数据类型,所以我可以使用toString方法.

问题是当我包含蛋白质= Double.valueOf(p).doubleValue(); 样式命令,程序强制立即关闭而不在logcat中留下任何信息.如果我将它们注释掉并设置一些虚拟数据,如protein = 1.0; 它没有任何问题.原始数据类型和解析double也是如此.此代码与普通java中的虚拟数据完美配合.我究竟做错了什么?

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);
Run Code Online (Sandbox Code Playgroud)

Izk*_*ata 72

我会这样做:

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
}
Run Code Online (Sandbox Code Playgroud)

编辑:"程序强制立即关闭,而不会在logcat中留下任何信息"

我不知道不会在logcat输出中留下信息,但强制关闭通常意味着有一个未捕获的异常 - 比如NumberFormatException.

  • 对于`kotlin`,你可以像这样使用`toDouble()`:`val d = textString.toDouble()` (2认同)

小智 18

试试这个:

double d= Double.parseDouble(yourString);
Run Code Online (Sandbox Code Playgroud)


jkj*_*jkj 5

您似乎将Double对象分配到本机值字段.这真的可以编译吗?

Double.valueOf()创建一个Double对象,因此不需要.doubleValue().

如果你想要原生字段,你需要将字段定义为double,然后使用.doubleValue()


Mik*_*der 2

使用 Double(String) 构造函数怎么样?所以,

protein = new Double(p);
Run Code Online (Sandbox Code Playgroud)

不知道为什么会有所不同,但可能值得一试。