# 将一个字符串转换为int。如果字符串为空，将int设为0[英] Converting a String to int. Set the int to 0 if String is null

### 问题描述

``` int block_id = Integer.parseInt(jsonarray.getJSONObject(i).getString("block_id"));
```

```int block_id = Converttoint(jsonarray.getJSONObject(i).getString("block_id"));
```

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

## 推荐答案

```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) {};
```

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

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

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

```Exception in thread "main" java.lang.NullPointerException
```

```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();
}
```

## 其他推荐答案

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

## 其他推荐答案

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