Reputation:
I am retrieving two values from a database, and need to divide them, but it gives me null pointer exception on line 1 and 2
1 int value1 = Integer.parseInt(rs.getString("value1"));
2 int value2 = Integer.parseInt(rs.getString("value2"));
3 double result = (double)value1/value2;
Error
java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:417)
at java.lang.Integer.parseInt(Integer.java:499)
Upvotes: 0
Views: 399
Reputation: 347314
You can do...
double result = 0;
String value1 = rs.getString("value1");
String value2 = rs.getString("value2");
if (value1 != null && value2 != null) {
try {
result = (double)(Integer.parseInt(value1) / (double)Integer.parseInt(value2))
} catch (NumberFormatException exp) {
// Handle or re-throw exception...
}
}
return result;
Or, if the column values are actually numbers...
double result = 0;
int value1 = rs.getInt("value1");
int value2 = rs.getInt("value2");
if (result2 > 0) {
result = (double)value1 / (double)value2;
}
return result;
Or, which might be simpler
double result = 0;
int value1 = rs.getDouble("value1");
int value2 = rs.getDouble("value2");
if (result2 > 0) {
result = value1 / value2;
}
return result;
Upvotes: 0
Reputation: 16158
You can parse only integer values which are in the form of Strings. For e.g. :
int i = Integer.parseInt("20");
int j = Integer.parseInt("NaN"); // throws NumberFormatException
Also, you should check values for null
to avoid NPE
as :
int v1=0, v2=0;
String value1 = rs.getString("value1");
if(value1 != null) {
v1 = Integer.parseInt(value1);
}
String value2 = rs.getString("value2");
if(value1 != null) {
v2 = Integer.parseInt(value2);
}
Upvotes: 0
Reputation: 1893
int value1 = Integer.parseInt(rs.getString("value1"));
int value2 = Integer.parseInt(rs.getString("value2"));
this line must be giving null thats why its giving null pointer exception
Upvotes: 0
Reputation: 213351
That is because, you are getting a null
value from your database, that you cannot pass to Integer.parseInt()
.
If one of the res.getString("value1");
, or res.getString("value2")
is null
, you will get an exception.
A better way is to wrap that conversion around try-catch
block, and in catch
block print the value of res.getString("value1")
; to check the actual value returned.
EDIT: -
Of course, you can also first print the value returned before you convert it to integer
to find if that is null
or not.
Upvotes: 1