English 中文(简体)
和机器人初创者: 空编辑文本
原标题:Android Beginner: Empty Edit Text

我正在创建一个程序, 将一个数字除以另一个数字。 我试图在出现空白编辑文本时添加代码以显示对话框, 但应用程序强制关闭。 这是我的代码 。

public class KdCalculator extends Activity implements OnClickListener{

    EditText kills;
    EditText deaths;
    TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.kd_activity);

        Button calculate = (Button)findViewById(R.id.ButtonCalculate);
            calculate.setOnClickListener(this);

        kills = (EditText)findViewById(R.id.EditTextKills);
        deaths = (EditText)findViewById(R.id.EditTextDeaths);

    }

    public void onClick(View paramView)
      { 
          boolean invalid = false;

          String str1 = kills.getText().toString();
          String str2 = deaths.getText().toString();

          if (str1.equals("") || str2.equals(""))
          {
              new AlertDialog.Builder(this)
                .setTitle("No Number")
                .setMessage("Please enter a number for both kills and deaths!")
                .setNeutralButton("Ok", null)
                .show();
              invalid = true;
          }

          double d1 = Double.parseDouble(str2);
          double d2 = Double.parseDouble(str1);

          if ((d1 == 0.0D) || (d2 == 0.0D))
          {
              new AlertDialog.Builder(this)
            .setTitle("Invalid Number")
            .setMessage("Please enter a number different than 0 for both kills and deaths!")
            .setNeutralButton("Ok", null)
            .show();
              invalid = true;
          }
          double d3 = d2 / d1;
          DecimalFormat localDecimalFormat = new DecimalFormat("#.###");
          String str3 = "Your K/D Ratio is : " + localDecimalFormat.format(d3);

          if(!invalid){
          new AlertDialog.Builder(this)
            .setTitle("K/D Ratio")
            .setMessage(str3)
            .setNeutralButton("Ok", null)
            .show();
          }
          invalid = false;
        }


}

日志错误为:

05-27 11:43:53.327: W/dalvikvm(6090): threadid=1: thread exiting with uncaught exception (group=0x40020b80)
05-27 11:43:53.357: E/AndroidRuntime(6090): FATAL EXCEPTION: main
05-27 11:43:53.357: E/AndroidRuntime(6090): java.lang.NumberFormatException: 
05-27 11:43:53.357: E/AndroidRuntime(6090):     at org.apache.harmony.luni.util.FloatingPointParser.parseDouble(FloatingPointParser.java:267)
05-27 11:43:53.357: E/AndroidRuntime(6090):     at java.lang.Double.parseDouble(Double.java:287)
05-27 11:43:53.357: E/AndroidRuntime(6090):     at com.blackops2.KdCalculator.onClick(KdCalculator.java:53)
05-27 11:43:53.357: E/AndroidRuntime(6090):     at android.view.View.performClick(View.java:2411)
05-27 11:43:53.357: E/AndroidRuntime(6090):     at android.view.View$PerformClick.run(View.java:8819)
05-27 11:43:53.357: E/AndroidRuntime(6090):     at android.os.Handler.handleCallback(Handler.java:587)
05-27 11:43:53.357: E/AndroidRuntime(6090):     at android.os.Handler.dispatchMessage(Handler.java:92)
05-27 11:43:53.357: E/AndroidRuntime(6090):     at android.os.Looper.loop(Looper.java:123)
05-27 11:43:53.357: E/AndroidRuntime(6090):     at android.app.ActivityThread.main(ActivityThread.java:4627)
05-27 11:43:53.357: E/AndroidRuntime(6090):     at java.lang.reflect.Method.invokeNative(Native Method)
05-27 11:43:53.357: E/AndroidRuntime(6090):     at java.lang.reflect.Method.invoke(Method.java:521)
05-27 11:43:53.357: E/AndroidRuntime(6090):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-27 11:43:53.357: E/AndroidRuntime(6090):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-27 11:43:53.357: E/AndroidRuntime(6090):     at dalvik.system.NativeStart.main(Native Method)
最佳回答

即使您的 EditText 是空的, 您仍然会从那些 EditText 中解析空的 < code> < digText , 因为您的代码在显示 AlertDialog 后继续被执行, 相反, 您应该从 onClick 方法返回, 以阻止任何计算( 当 EditText 是空的或者没有填满时) :

public void onClick(View paramView) { 
          String str1 = kills.getText().toString();
          String str2 = deaths.getText().toString();

          if (str1.equals("") || str2.equals("")) {
              new AlertDialog.Builder(this)
                .setTitle("No Number")
                .setMessage("Please enter a number for both kills and deaths!")
                .setNeutralButton("Ok", null)
                .show();
                return;   
          }
          double d1 = Double.parseDouble(str2);
          double d2 = Double.parseDouble(str1);
          if ((d1 == 0.0D) || (d2 == 0.0D)) {
              new AlertDialog.Builder(this)
            .setTitle("Invalid Number")
            .setMessage("Please enter a number different than 0 for both kills and deaths!")
            .setNeutralButton("Ok", null)
            .show();
            return;
          }
          double d3 = d2 / d1;
          DecimalFormat localDecimalFormat = new DecimalFormat("#.###");
          String str3 = "Your K/D Ratio is : " + localDecimalFormat.format(d3);

          new AlertDialog.Builder(this)
            .setTitle("K/D Ratio")
            .setMessage(str3)
            .setNeutralButton("Ok", null)
            .show();
        }
问题回答

尝试在调用 str1 & str2 之前记录 Double.parseDouble(String) ; 您可以使用 Log.d(String, String) 来做到这一点。

根据堆叠跟踪, 无法将其中的值之一转换成数字 。

我通常会做的是将任何数字格式调用设置到 try... captain block - 这种操作可能有许多错误。 这可能是避免此代码中发生任何进一步崩溃的最成功方法 。

试试这个...

DecimalFormat localDecimalFormat = new DecimalFormat("0.000");

仅举个例子, 试着检查字符串 string str1 和 str2, 并谨慎小心。 双倍不能以零差错进行分隔 。

我不知道,但试试这个...

public class KdCalculator extends Activity implements OnClickListener
{    
    double d1 = 0.0;
    double d2 = 0.0;    
    EditText kills;
    EditText deaths;
    TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.kd_activity);

        Button calculate = (Button)findViewById(R.id.ButtonCalculate);
            calculate.setOnClickListener(this);

        kills = (EditText)findViewById(R.id.EditTextKills);
        deaths = (EditText)findViewById(R.id.EditTextDeaths);

    }

    public void onClick(View paramView)
      { 
          boolean invalid = false;

          String str1 = kills.getText().toString();
          String str2 = deaths.getText().toString();

          if (str1.equals("") || str2.equals(""))
          {
              new AlertDialog.Builder(this)
                .setTitle("No Number")
                .setMessage("Please enter a number for both kills and deaths!")
                .setNeutralButton("Ok", null)
                .show();
              invalid = true;
          }

          d1 = Double.parseDouble(str2);
          d2 = Double.parseDouble(str1);

          if ((d1 == 0.0D) || (d2 == 0.0D))
          {
              new AlertDialog.Builder(this)
            .setTitle("Invalid Number")
            .setMessage("Please enter a number different than 0 for both kills and eaths!")
            .setNeutralButton("Ok", null)
            .show();
              invalid = true;
          }
          double d3 = d2 / d1;
          DecimalFormat localDecimalFormat = new DecimalFormat("#.###");
          String str3 = "Your K/D Ratio is : " + localDecimalFormat.format(d3);

          if(!invalid){
          new AlertDialog.Builder(this)
            .setTitle("K/D Ratio")
            .setMessage(str3)
            .setNeutralButton("Ok", null)
            .show();
          }
          invalid = false;
        }
}

并且确保计算器中的输入有类似 2. 0 或 2. 2 或 (双格式) 的输入, 不要使用逗号...





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签