【问题标题】:Throws exception while Type casting from String to Int.从 String 类型转换为 Int 时引发异常。
【发布时间】:2017-09-08 07:46:40
【问题描述】:

我不知道这里出了什么问题。 代码片段

       b1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                String s1=SpinnerObj.getSelectedItem().toString();
                String n1=s1.substring(s1.indexOf("Rs")+2,s1.length()-1);
                int ns1=Integer.parseInt(String.valueOf(n1));//Couldnt cast and throws Exception
                Toast.makeText(getBaseContext(),""+ns1,Toast.LENGTH_LONG).show();
                Intent i = new Intent(getBaseContext(),OrderPlaced.class);
                startActivity(i);
            }
                catch (NumberFormatException nfe) {
                Toast.makeText(getBaseContext(), "gg", Toast.LENGTH_LONG).show();
            }
        }});

我在这里尝试将从 Spinner 获取的字符串类型转换为整数以进行计算。

【问题讨论】:

  • n1 的值是多少?
  • 添加错误logcat ...
  • 当String超过整数时有时无法将其转换为int。它会抛出异常。尝试使用使用字符串值并检查一次
  • 确保您的 n1 字符串中没有空格或任何其他字符串值,它必须只包含数值。 OR 可能是 n1 值为空。也发布 logcat 和您的字符串以获得更清晰的想法。
  • 我的微调器值为“Havells 风扇(900 卢比)”。并且 m 在 n1 中得到 900。

标签: android casting


【解决方案1】:

IMO 你正在使用不正确的子字符串的第一个索引尝试下面的代码

  String test = "Havells fan(Rs 900)";
        String n1=test.substring(test.indexOf("Rs")+3,test.length()-1);\\ use +3 instead of +2
        int ns1 = Integer.parseInt(String.valueOf(n1));
        Toast.makeText(getBaseContext(),""+ns1,Toast.LENGTH_LONG).show();

【讨论】:

    【解决方案2】:

    也许字符串有一个空格。 你应该使用n1.tirm()

    【讨论】:

      【解决方案3】:

      根据您在 cmets 中提供的字符串:Havells fan(Rs 900) 您在计算数字的起始索引时在字符串中包含一个空格,因为s1.indexOf("Rs")+2(此计算将给出 14)将指向空格(索引 14) ,而不是 9(索引 15)。对于提出的解决方案,您可以使用任何现有的答案来修剪字符串 (n1.trim()) 或在计算起始索引时计算空格字符 (s1.indexOf("Rs")+3)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-05-20
        • 2018-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-11
        相关资源
        最近更新 更多