java - 当我尝试获取 Int 时我的应用程序停止

标签 java android parsing int

我正在尝试制作一个接受输入并自动将其更改为 int 的应用程序。但是,当它尝试获取 int 时,应用程序会自动停止。以下是完整代码...

    public class MainActivity extends Activity implements OnClickListener{  

        @Override
        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            Button calculate = (Button)findViewById(R.id.calculateTip);
            calculate.setOnClickListener(this);

        }//end onCreate

    public void onClick(View v) {

            EditText money = (EditText)findViewById(R.id.bill);
            int bill = Integer.parseInt(money.getText().toString());
            money.setText("Event Processed");

    }//end onClick

    }//end MainActivity

最佳答案

我怀疑应用程序正在停止,因为您尝试解析的值实际上并不是整数。您应该将该代码放入 try catch 中。

即:

    public void onClick(View v) {

       EditText money;
       try
       {
            money = (EditText)findViewById(R.id.bill);

             // This check makes sure that the EditText is returning the correct object.
            if(money != null)
            {
              int bill = Integer.parseInt(money.getText().toString());
              money.setText("Event Processed");
            }
       }
       catch(NumberFormatException e)
       {
       // If we get in here that means the inserted value was not an Integer. So do               something.
       //ie:
        money.setText("Please enter a value amount" );
        }
    }//end onClick

无论如何,您应该将此代码放在 try catch 中以保持数据完整性。

希望这有帮助! 干杯。

关于java - 当我尝试获取 Int 时我的应用程序停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12682688/

相关文章:

android - MapFragment 返回 null

c - 我在C编程中找不到字符串中的大写字母

java - 我们应该在 hibernate 中创建域类时实现 Serialized 接口(interface)吗

java - ScheduledExecutorService 可抛出丢失

java - 如何获取每个子弹的起点? Libgdx 简单游戏

android - Eclipse - Android UI 设计极其滞后

javascript - D3条形图不解析csv

适合 JavaME 语法的编译器推荐?

java - 信息 : API 'variant.getMergeResources()' is obsolete and has been replaced with 'variant.getMergeResourcesProvider()'

java - 是否有循环队列的非并发(ArrayBlockingQueue 除外)标准实现?