java.lang.numberformatexception:无效双:“”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18672456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 10:04:13  来源:igfitidea点击:

java.lang.numberformatexception: invalid double: " "

javaandroid

提问by no0bCoder

getting an error of invalid Double java.lang.numberformatexception invalid double: "" what is the reason for this

得到一个 invalid Double 的错误 java.lang.numberformatexception invalid double: "" 这是什么原因

Activity 1

活动一

package com.example.solarcalculator;

        import android.os.Bundle;
        import android.widget.Button;
        import android.annotation.SuppressLint;
        import android.app.Activity;
        import android.view.Menu;
        import android.view.View;
        import android.view.View.OnClickListener;
        import android.widget.EditText;
        import android.app.AlertDialog;
        import android.content.Intent;

        @SuppressLint("UseValueOf")
        public class MainActivity extends Activity {
            private EditText input1;
            private EditText input2;
            private EditText input3;
            private EditText input4;
            private EditText input5;
            private MainActivity mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_main);

        input5 = (EditText) findViewById(R.id.input5);
        Button button1 = (Button) findViewById(R.id.button1);
        input4 = (EditText) findViewById(R.id.input4);
        input1 = (EditText) findViewById(R.id.input1);
        input2 = (EditText) findViewById(R.id.input2);
        input3 = (EditText) findViewById(R.id.input3);
        button1.setOnClickListener(new OnClickListener() {

            @SuppressWarnings("unused")
            private AlertDialog show;

            @SuppressLint("UseValueOf")
            @Override
            public void onClick(View arg0) {
                if (  (input4.getText().toString() == " ") 
                        || (input4.getText().length() ==0) ||
                                                (input5.getText().length() == 0)                         
                        || (input5.getText().toString() == " ")){
                show = new      AlertDialog.Builder(mContext).setTitle("Error")
                            .setMessage("Some inputs are empty")
                            .setPositiveButton("OK", null).show();
                }
    else if ((input1.getText().length() != 0) &&
        (input3.getText().length() ==0) && (input2.getText().length() ==    0)){
                     double w = new Double(input3.getText().toString());
                     double t = new Double(input4.getText().toString());
                     double x = new Double(input5.getText().toString());
                     float e = 7;
                     double num = 1000*x;
                     double den = w*t*e;
                     double payback = num/den;
                     double money = w*t*e/1000;
         Intent intent = new Intent(MainActivity.this, Power.class);
                     intent.putExtra("payback", payback);
                     intent.putExtra("money", money);
                     startActivity(intent);

                }
    else if ((input1.getText().length() == 0) &&   (input3.getText().length() != 0) &&
                                (input2.getText().length() != 0)){
                     double t = new    
                                     Double(input4.getText().toString());
                     double x = new Double(input5.getText().toString());
                     double v = new Double(input2.getText().toString());
                     double i = new Double(input3.getText().toString());
                     float e = 7;
                     double num = 1000*x;
                     double den = v*i*t*e;
                     double payback = num/den;
                     double money = v*i*t*e/1000;
             Intent intent = new Intent(MainActivity.this, Power.class);
                     intent.putExtra("payback", payback);
                     intent.putExtra("money", money);
                     startActivity(intent);

                }
                else {
                    double t = new Double(input4.getText().toString());
                     double x = new Double(input5.getText().toString());
                     double v = new Double(input2.getText().toString());
                     double i = new Double(input3.getText().toString());
                     float e = 7;
                     double num = 1000*x;
                     double den = v*i*t*e;
                     double payback = num/den;
                     double money = v*i*t*e/1000;
               Intent intent = new Intent(MainActivity.this, Power.class);
                     intent.putExtra("payback", payback);
                     intent.putExtra("money", money);
                     startActivity(intent);

                }
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

       }

Activity2

活动2

package com.example.solarcalculator;

    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.TextView;
   @SuppressLint("NewApi")
     public class Power extends Activity {

private double money;
private double payback;

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.power);
    payback = getIntent().getDoubleExtra("payback",0);
    money = getIntent().getDoubleExtra("money", 0);
    TextView pay = (TextView) findViewById(R.id.textView2);
    String payback1 = Double.toString(payback);
    pay.setText(payback1);
    TextView mon = (TextView) findViewById(R.id.textView4);
    String money1 = Double.toString(money);
    mon.setText(money1);

     }
    }

I am getting java.lang.numberformatexception invalid double: "" error in logcat anyone please help

我收到 java.lang.numberformatexception invalid double: "" error in logcat 任何人请帮忙

采纳答案by flx

The reason is, that "" is not a valid double. You need to test the String before or catch such exceptions

原因是,“”不是有效的双倍。您需要先测试 String 或捕获此类异常

double w;

try {
    w = new Double(input3.getText().toString());
} catch (NumberFormatException e) {
    w = 0; // your default value
}

回答by Raghunandan

You should do as below. Put it inside a try catch block

你应该做如下。把它放在一个 try catch 块中

   double w = new Double(input3.getText().toString());

回答by Aditya Naique

Better to also test for .equals("")along with null.

最好也.equals("")null.

Consider you have an afterTextChanged listener on an EditText. When you back press and clear the entered text, it'll pass != null, but still have "".

假设您在 EditText 上有一个 afterTextChanged 侦听器。当你回按并清除输入的文本时,它会通过!= null,但仍然有"".

This worked for me:

这对我有用:

    double myDouble;

    String myString = ((EditText) findViewById(R.id.editText1)).getText().toString();

    if (myString != null && !myString.equals("")) {
        myDouble = Double.valueOf(myString);
    } else {
        myDouble = 0;
    }

回答by Forntoh

The value of the double depends on the language of the device.For example, for devices in french the number 0.179927becomes 0,179927which will always throw a NumberFormatExceptionwhen parsing it to doublebecause of the comma.

double 的值取决于设备的语言。例如,对于法语设备,数字0.179927变为0,179927,由于逗号,NumberFormatException在解析它时总是会抛出 a double

You need to change the separator from a commato a point. You can change the separator either by setting a locale or using the DecimalFormatSymbols.

您需要将分隔符从 a 更改comma为 a point。您可以通过设置区域设置或使用DecimalFormatSymbols.

If you want the grouping separator to be a point, you can use a european locale:

如果您希望分组分隔符是一个点,您可以使用欧洲语言环境:

NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN);
DecimalFormat df = (DecimalFormat)nf;

Alternatively you can use the DecimalFormatSymbolsclass to change the symbols that appear in the formatted numbers produced by the formatmethod. These symbols include the decimal separator, the grouping separator, the minus sign, and the percent sign, among others:

或者,您可以使用DecimalFormatSymbols该类来更改出现在该format方法生成的格式化数字中的符号。这些符号包括小数点分隔符、分组分隔符、减号和百分号等:

DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(currentLocale);
otherSymbols.setDecimalSeparator(',');
otherSymbols.setGroupingSeparator('.'); 
DecimalFormat df = new DecimalFormat(formatString, otherSymbols);

回答by Akshay Chopra

Basically, you need to testwhether the stringthat you want to convert into double is empty or not.

基本上,您需要测试要转换为 double的字符串是否为空

If it is empty, then you can just initialise itwith some value and then proceed further.

如果它是空的,那么你可以用一些值初始化它,然后继续进行。

For example:

例如:

if(myString.isEmpty()){
myString = ""+0.0;
}
double answer = Double.parseDouble(myString);