【问题标题】:Convert java.lang.String to int in android在android中将java.lang.String转换为int
【发布时间】:2012-11-21 10:09:35
【问题描述】:

如何在 Android 中将 java.lang.String 转换为 int? 我写了这段代码,但它不起作用:

public static String code;
...
db.insertQuote(Integer.parseInt(code));

我使用此代码,当我阅读 NFC 标签时,我希望运行此功能,但它给了我一个错误,因为我使用真实的手机进行测试,所以我无法理解发生了什么。

【问题讨论】:

  • 为什么会失败?错误是什么? “因为我是用真机测试的,所以我不明白发生了什么”oO 怎么回事?
  • Logcat 仍然存在用于“真正的移动”...
  • 它让我在移动设备中强制关闭,但是当我手动使用 code="09877776" 时,它可以工作!
  • 你的字符串是空的吗?你在哪里给它一个价值?显示相关代码。
  • 当心你的字符串转换成整数,你会失去填充 0...

标签: android string tags integer


【解决方案1】:
    int i=Integer.parseInt(stringvalue);

【讨论】:

    【解决方案2】:

    所以,假设代码具有除数字以外的其他值,您应该调试并测试code 的值,如果它为空白,它也会抛出NumberFormatException,或者如果它的 NullPointerException,那么字符串代码可能尚未初始化。

    【讨论】:

      【解决方案3】:

      您确定在调用Integer.parseInt(Code) 之前正确初始化Code 吗? 如果Code 仍然只是定义,但没有初始化(没有分配给Code),那么这就是你的问题。
      除此之外,您必须确保 Code 确实是一个数字,所以我建议如下:

      public static String Code;
      ... //rest of your code here
      if(Code != null)
      {
        try
        {
          db.insertQuote(Integer.parseInt(Code));
        }
        catch(NumberFormatException e)
        {
          //execution will get here if Code is not a number
          //insert code to handle this chase
        }
      }
      

      【讨论】:

        【解决方案4】:

        最简单的答案是:

               int i = Integer.parseInt(StringValue);
        

        【讨论】:

          【解决方案5】:
          String number;
          int x = Integer.valueOf(number);
          

          【讨论】:

            猜你喜欢
            • 2020-11-14
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-11-12
            • 1970-01-01
            • 1970-01-01
            • 2020-10-17
            • 2021-09-12
            相关资源
            最近更新 更多