将String转换为int。如果String为null,则将int设置为0

时间:2016-09-27 14:03:25

标签: java android

我有一个功能可以在String中保存Android数据,但我必须将Integer数据转换为String

每当null0我想保存为null

以下是我的代码,只要值为 int block_id = Integer.parseInt(jsonarray.getJSONObject(i).getString("block_id"));

,代码就会失败
block_id

上面的Integer转换为0

这是我决定要做的事情但仍无法将字符串值转换为null int block_id = Converttoint(jsonarray.getJSONObject(i).getString("block_id"));

convertToInt

然后是函数 public static Integer convertToInt(String str) { int n=0; if(str != null) { n = Integer.parseInt(str); } return n; }

{{1}}

我应该如何改变它,让它发挥作用?

12 个答案:

答案 0 :(得分:24)

只需使用内置方法JSONObject#getInt(String),如果它是 mInterstitialAd = new InterstitialAd(adContext); mInterstitialAd.setAdUnitId("xxxxxxxxxxx"); AdRequest adRequest = new AdRequest.Builder() .setGender(AdRequest.GENDER_MALE) .setBirthday(new GregorianCalendar(1993, 1, 1).getTime()) .build(); mInterstitialAd.loadAd(adRequest); 或通过int,它会自动将值转换为Integer.parseInt(String)如果是String则调用Number#intValue()。为避免在您的密钥不可用时出现异常,只需先检查Number实例是否包含使用JSONObject#has(String)的密钥,这足以确保安全,因为密钥不能具有JSONObject值,它存在一个非null值,或者它不存在。

null

答案 1 :(得分:15)

使用try-catch的inbuild构造而不是编写自己的函数。您的问题是,jsonarrayjsonarray.getJSONObject(i)或值本身是null,您在空引用上调用方法。请尝试以下方法:

int block_id = 0;        //this set's the block_id to 0 as a default.
try {
    block_id =  Integer.parseInt(jsonarray.getJSONObject(i).getString("block_id"));    //this will set block_id to the String value, but if it's not convertable, will leave it 0.
} catch (Exception e) {};

在Java中,异常用于标记意外情况。例如,将非数字String解析为数字(NumberFormatException)或在null引用(NullPointerException)上调用方法。你可以通过多种方式捕捉它们。

try{
    //some code
} catch (NumberFormatException e1) {
    e.printStackTrace()     //very important - handles the Exception but prints the information!
} catch (NullPointerException e2) {
    e.printStackTrace();
}

或使用这一事实,他们都扩展Exception

try {
    //somecode
} catch (Exception e) {
    e.printStackTrace;
};

或者自Java 7以来:

try {
    //somecode
} catch (NullPointerException | NumberFormatException e) {
    e.printStackTrace;
};

注意

我相信,你会仔细阅读答案,请记住,在StackOverflow上我们需要包含你的异常的StackTrace的Minimal, Complete, and Verifiable example。在您的情况下,它可能从以下开始:

Exception in thread "main" java.lang.NullPointerException

然后,调试就容易多了。没有它,它只是在猜测。

修改: 根据接受的答案

接受的答案很好,并且可以使用,因为使用密钥block_id存储的值将是数字。如果它不是数字,您的应用程序将崩溃。

而不是:

JSONObject jObj = jsonarray.getJSONObject(i);
int block_id = jObj.has("block_id") ? jObj.getInt("block_id") : 0;

应该使用:

int block_id;
try{
    JSONObject jObj = jsonarray.getJSONObject(i);
    block_id = jObj.has("block_id") ? jObj.getInt("block_id") : 0;
} catch (JSONException | NullPointerException e) {
    e.printStackTrace();
}

答案 2 :(得分:9)

除了其他答案中给出的方法之外,还有一种方法可以做到这一点。

String blockId=jsonarray.getJSONObject(i).getString("block_id");
int block_id = blockId==null ? 0 :  Integer.parseInt(blockId);

答案 3 :(得分:8)

您可以查看NumberFormatException。对于案件,Integer.parseInt()会抛出NumberFormatException

  • Stringnull
  • String为空(""
  • 由于任何其他原因,
  • String无法转换为int(例如String"aff""1.25"

基本上,它将处理所有可能的非整数情况。

代码示例:

private static int convertStringToInt(String str){
    int x = 0;
    try{
        x = Integer.parseInt(str);
    }catch(NumberFormatException ex){
        //TODO: LOG or HANDLE
    }
    return x;
}

答案 4 :(得分:7)

您可以使用以下方法

String id = jsonarray.getJSONObject(i).getString("block_id")
int blockId = getBlockId(id);

@NonNull
private Integer getBlockId(String id) {
    Integer blockId= 0;
    try {
        blockId= Integer.parseInt(id);
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }
    return blockId;
}

答案 5 :(得分:6)

String toBeParsedStr="1234";
int parsedInt=toBeParsedStr!=null&&toBeParsedStr.matches("[0-9]+")?Integer.parseInt(toBeParsedStr):0;

答案 6 :(得分:6)

试试这个

 int block_id = (jsonarray.getJSONObject(i).has(block_id)) ? jsonarray.getJSONObject(i).getInt("block_id") : 0;

答案 7 :(得分:3)

您可以使用Integer.getInteger("30").intValue()

答案 8 :(得分:2)

optInt

return条件和多个代码可以简单地用default value函数替换为一行,只需

1。)0 stringjObj.optInt("block_id",defaultvalue); 如果没有值(取决于您使用的变体)。

2。)如果值为jObj.optInt("block_id");

,请尝试转换该值

3。)如果缺少键或值,只需没有null或NumberFormat例外

Android文档

int optInt (String name)

int optInt (String name, int fallback)

Maven的中央

int optInt(String key, int defaultValue)

如果没有可用值,则获取指定的默认值

  

获取与键关联的可选int值,或默认值if   没有这样的密钥,或者该值不是数字。如果值是   一个字符串,将尝试将其评估为数字。

int block_id = jObj.optInt("block_id",5); 

如果没有可用值,则将默认值设为0

  

获取与键关联的可选int值,如果存在则为零   没有这样的键或者值不是数字。如果值是一个字符串,   将尝试将其评估为数字。

block_id

e.g

int block_id_0 = jObj.optInt("block_id"); 
如果没有可用的键/值,

block_id_0将为5

docs
如果没有可用的键/值,

$scope.$on将为0

此函数的其他变体也可用于其他数据类型,请尝试上面的$scope.$emit链接。

答案 9 :(得分:1)

String str = "...";
// suppose str becomes null after some operation(s).
int number = 0;
try
{
    if(str != null)
      number = Integer.parseInt(str);
}
catch (NumberFormatException e)
{
    number = 0;
}

答案 10 :(得分:1)

注意..你也可以这样写

 public static Integer convertToInt(String str) {
    int n=0;
    if(str != null && str.length()>0) {
        n = Integer.parseInt(str);
    }
    return n;
}

但是try / catch方法更有效,更简单,如果字母进入字符串内部就不会导致系统退出(只是值得一提)

另外,重要的是要注意写下相同的等式:

if(str != null & str.length()>0) {}

或者那样:

if(str.length()>0 && str != null) {}

会导致操作失败,因为它会尝试计算String,即使它是null

希望我回答你的所有问题

答案 11 :(得分:-1)

只有当param为空string而不是null时,您的函数才能正常工作 如果参数为空Integer.parseInt,则NumberFormatException会抛出//profilePic is the button //friend is a coredata object received from another view. picIndex is stored as int16 in the coredata profilePic.setImage(UIImage(named: imgArray[friend.picIndex]), forState: UIControlState.Normal); 而不是返回0

相关问题