将编辑文本值转换为双精度值 - 始终为零(android studio,java)



我正在制作一个安卓应用程序 - 当我设法运行问题时,我遇到了很多错误。我必须获取编辑文本的值并将其转换为双精度值,起初它根本不起作用(应用程序因此崩溃(,然后我设法让它运行,但现在它总是零

例如,每次方法c2f称为resukt时,都是32 ...

**Main activity:**
input = (EditText) findViewById(R.id.input);
    convert = (Button) findViewById(R.id.convert);
    result = (TextView) findViewById(R.id.result);
    c2f = (RadioButton) findViewById(R.id.c2f);
    c2k = (RadioButton) findViewById(R.id.c2k);
    f2c = (RadioButton) findViewById(R.id.f2c);
    f2k = (RadioButton) findViewById(R.id.f2k);
    k2c = (RadioButton) findViewById(R.id.k2c);
    k2f = (RadioButton) findViewById(R.id.k2f);
    double w;
    try {
        w = new Double(input.getText().toString());
    } catch (NumberFormatException e) {
        w = 0;
    }

    final double finalW = w;
    convert.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {
            if (c2f.isChecked())
            {
                result.setText(Converter.c2f(finalW)+ "F");
            } else if (c2k.isChecked())
            {
                result.setText(Converter.c2k(finalW)+ "K");
            } else if (f2c.isChecked())
            {
                result.setText(Converter.f2c(finalW)+ "C");
            } else if (f2k.isChecked())
            {
                result.setText(Converter.f2k(finalW)+ "K");
            } else if (k2c.isChecked())
            {
                result.setText(Converter.k2c(finalW)+ "C");
            } else if (k2f.isChecked())
            {
                result.setText(Converter.k2f(finalW)+ "F");
            }
        }
    });

}}

类转换

public class Converter

{ 公共静态双 C2F (双 W ( {返回 W*9/5+32;} 公共静态双 C2K (双 W ( { 返回 w+273.15; } 公共静态双F2C(双W( { 返回 (W-32(*5/9; } 公共静态双 F2K (双 W ( {返回 (W+ 459.67(*5/9;} 公共静态双K2C(双W( { 返回 W-273.15; } 公共静态双K2F(双W( { 返回 w*1.8 - 459.67; }}

/**Simply you can use below code snipet**/
 <EditText
    android:id="@+id/input"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="number or numberDecimal"
    android:lines="1"
    android:textStyle="normal"
    android:maxLines="1" />
 try
 {
    double value = Double.valueOf(input.getText().toString());
 }
 catch (NumberFormatException ex)
 {
    ex.printStackTrace();
 }

这是因为抛出了异常,并且您在 catch 块中设置了w = 0;。使用这个:

try {
    w = Double.parseDouble(input.getText().toString().trim());
} catch (NumberFormatException e) {
    e.printStackTrace();
    w = 0;
}

您也可以考虑将编辑文本的输入类型设置为xml中的数字:

<EditText
    android:id="@+id/edit_text"
    android:maxLines="1"
    android:inputType="numberDecimal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

最新更新