Greetings,
I'm trying to validate whether my integer is null. If it is, I need to prompt the user to enter a value. My background is Perl, so my first attempt looks like this:
int startIn = Integer.parseInt (startField.getText());
if (startIn) {
JOptionPane.showMessageDialog(null,
"You must enter a number between 0-16.","Input Error",
JOptionPane.ERROR_MESSAGE);
}
This does not work, since Java is expecting boolean logic.
In Perl, I can use "exists" to check whether hash/array elements contain data with:
#items = ("one", "two", "three");
##items = ();
if (exists($items[0])) {
print "Something in \#items.\n";
}
else {
print "Nothing in \#items!\n";
}
Is there a way to this in Java? Thank you for your help!
Jeremiah
P.S. Perl exists info.
parseInt() is just going to throw an exception if the parsing can't complete successfully. You can instead use Integers, the corresponding object type, which makes things a little bit cleaner. So you probably want something closer to:
Integer s = null;
try {
s = Integer.valueOf(startField.getText());
}
catch (NumberFormatException e) {
// ...
}
if (s != null) { ... }
Beware if you do decide to use parseInt()! parseInt() doesn't support good internationalization, so you have to jump through even more hoops:
try {
NumberFormat nf = NumberFormat.getIntegerInstance(locale);
nf.setParseIntegerOnly(true);
nf.setMaximumIntegerDigits(9); // Or whatever you'd like to max out at.
// Start parsing from the beginning.
ParsePosition p = new ParsePosition(0);
int val = format.parse(str, p).intValue();
if (p.getIndex() != str.length()) {
// There's some stuff after all the digits are done being processed.
}
// Work with the processed value here.
} catch (java.text.ParseFormatException exc) {
// Something blew up in the parsing.
}
Try this:
Integer startIn = null;
try {
startIn = Integer.valueOf(startField.getText());
} catch (NumberFormatException e) {
.
.
.
}
if (startIn == null) {
// Prompt for value...
}
ints are value types; they can never be null. Instead, if the parsing failed, parseInt will throw a NumberFormatException that you need to catch.
There is no exists for a SCALAR in Perl, anyway. The Perl way is
defined( $x )
and the equivalent Java is
anInteger != null
Those are the equivalents.
exists $hash{key}
Is like the Java
map.containsKey( "key" )
From your example, I think you're looking for
if ( startIn != null ) { ...
For me just using the Integer.toString() method works for me just fine. You can convert it over if you just want to very if it is null. Example below:
private void setCarColor(int redIn, int blueIn, int greenIn)
{
//Integer s = null;
if (Integer.toString(redIn) == null || Integer.toString(blueIn) == null || Integer.toString(greenIn) == null )
I don't think you can use "exists" on an integer in Perl, only on collections. Can you give an example of what you mean in Perl which matches your example in Java.
Given an expression that specifies a hash element or array element, returns true if the specified element in the hash or array has ever been initialized, even if the corresponding value is undefined.
This indicates it only applies to hash or array elements!
This should help.
Integer startIn = null;
// (optional below but a good practice, to prevent errors.)
boolean dontContinue = false;
try {
Integer.parseInt (startField.getText());
} catch (NumberFormatException e){
e.printStackTrace();
}
// in java = assigns a boolean in if statements oddly.
// Thus double equal must be used. So if startIn is null, display the message
if (startIn == null) {
JOptionPane.showMessageDialog(null,
"You must enter a number between 0-16.","Input Error",
JOptionPane.ERROR_MESSAGE);
}
// (again optional)
if (dontContinue == true) {
//Do-some-error-fix
}
Related
I have a function which saves Android data in sqlite but I have to convert the String data to an Integer.
Whenever the String is null i would like to save as 0
The following is my code which fails whenever the value is null
int block_id = Integer.parseInt(jsonarray.getJSONObject(i).getString("block_id"));
The block_id above is converted to an Integer.
This is what i have decided to do but still it fails to convert the string value to 0 whenever its null.
int block_id = Converttoint(jsonarray.getJSONObject(i).getString("block_id"));
Then the function convertToInt
public static Integer convertToInt(String str) {
int n=0;
if(str != null) {
n = Integer.parseInt(str);
}
return n;
}
How should I change it, to make it work?
Simply use the built-in method JSONObject#getInt(String), it will automatically convert the value to an int by calling behind the scene Integer.parseInt(String) if it is a String or by calling Number#intValue() if it is a Number. To avoid an exception when your key is not available, simply check first if your JSONObject instance has your key using JSONObject#has(String), this is enough to be safe because a key cannot have a null value, either it exists with a non null value or it doesn't exist.
JSONObject jObj = jsonarray.getJSONObject(i);
int block_id = jObj.has("block_id") ? jObj.getInt("block_id") : 0;
Instead of writing your own function use the inbuild construction of try-catch. Your problem is, that jsonarray or jsonarray.getJSONObject(i) or the value itself is a null and you call a method on null reference. Try the following:
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) {};
In Java Exceptions are used for marking unexpected situations. For example parsing non-numeric String to a number (NumberFormatException) or calling a method on a null reference (NullPointerException). You can catch them in many ways.
try{
//some code
} catch (NumberFormatException e1) {
e.printStackTrace() //very important - handles the Exception but prints the information!
} catch (NullPointerException e2) {
e.printStackTrace();
}
or using the fact, that they all extend Exception:
try {
//somecode
} catch (Exception e) {
e.printStackTrace;
};
or since Java 7:
try {
//somecode
} catch (NullPointerException | NumberFormatException e) {
e.printStackTrace;
};
Note
As I believe, that you'll read the answer carefully, please have in mind, that on StackOverflow we require the Minimal, Complete, and Verifiable example which include the StackTrace of your exception. In your case it probably starts with the following:
Exception in thread "main" java.lang.NullPointerException
Then, debugging is much easier. Without it, it's just guessing.
Edit: According to the accepted answer
The accepted answer is good and will work as long, as the value stored with key: block_id will be numeric. In case it's not numeric, your application will crash.
Instead of:
JSONObject jObj = jsonarray.getJSONObject(i);
int block_id = jObj.has("block_id") ? jObj.getInt("block_id") : 0;
One should use:
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();
}
There is one more way to do this apart from the methods given in rest of the answers.
String blockId=jsonarray.getJSONObject(i).getString("block_id");
int block_id = blockId==null ? 0 : Integer.parseInt(blockId);
You can check for NumberFormatException. Integer.parseInt() will throw NumberFormatException for cases:
String is null
String is empty ("")
String cannot be converted to int for any other reason (say String is "aff" or "1.25")
Basically, it will handle all possible non-integer cases.
Code Example:
private static int convertStringToInt(String str){
int x = 0;
try{
x = Integer.parseInt(str);
}catch(NumberFormatException ex){
//TODO: LOG or HANDLE
}
return x;
}
You can use following method,
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;
}
String toBeParsedStr="1234";
int parsedInt=toBeParsedStr!=null&&toBeParsedStr.matches("[0-9]+")?Integer.parseInt(toBeParsedStr):0;
Try this
int block_id = (jsonarray.getJSONObject(i).has(block_id)) ? jsonarray.getJSONObject(i).getInt("block_id") : 0;
you can use Integer.getInteger("30").intValue()
int block_id_0 = jObj.optInt("block_id");
The ternary condition and multiple code can simply be replaced with optInt function in a single line, which simply
1.) return the default value or 0 if no value is there (depends upon the variant you are using).
2.) Try to convert the value, if the value is available as string
3.) Simply No null or NumberFormat exceptions at all in case of missing key or value
Android docs
int optInt (String name)
int optInt (String name, int fallback)
Maven-Central
int optInt(String key, int defaultValue)
To get a specified default value if no value available
Get an optional int value associated with a key, or the default if
there is no such key or if the value is not a number. If the value is
a string, an attempt will be made to evaluate it as a number.
jObj.optInt("block_id",defaultvalue);
or
To get a default value as 0 if no value available
Get an optional int value associated with a key, or zero if there is
no such key or if the value is not a number. If the value is a string,
an attempt will be made to evaluate it as a number.
jObj.optInt("block_id");
e.g
int block_id = jObj.optInt("block_id",5);
block_id will be 5 if no key/value available
int block_id_0 = jObj.optInt("block_id");
block_id_0 will be 0 if no key/value available
There are other variant of this function available for other datatypes as well , try the docs link above.
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;
}
Notice.. you could also write it like that
public static Integer convertToInt(String str) {
int n=0;
if(str != null && str.length()>0) {
n = Integer.parseInt(str);
}
return n;
}
but the try/catch method is way more effective and simple and will not cause a system exit if a letter get inside the String (just worth mentioning)
also, it is important to notice that writing the same equation like that:
if(str != null & str.length()>0) {}
or like that:
if(str.length()>0 && str != null) {}
can cause the operation to fail because it will try to count the String even if it is null
Hope I responded to all your questions
Your function should work fine only when the param is an empty string instead of null
If the param is empty string ,Integer.parseInt would throw a NumberFormatException instead of return 0
I'm trying to find an easy way to perform multiple null checks/ replacements in multiple variables in Java.
I have an object with about 20 String variables. In the constructor I want to check if any of the variable values are null. If they are null I want to replace them with an empty String. I could perform a series of if statements but I feel like there must be a cleaner way to do this.
Unless you want to resort to reflection (which I strongly discourage) your best bet is probably to create a helper method (return s == null ? "" : s) and do
field1 = nullToEmpty(field1);
field2 = nullToEmpty(field2);
...
If you already depend on Apache Commons or Guava you can use StringUtils.defaultString or Strings.nullToEmpty.
I agree with aioobe, using reflection is something you should avoid like the plague. But if you are blessed with a project where for example you have to mock a REST interface manually and the objects that come via this interface have tons of Integer, String, Double etc. inside I think you have no other choice.
Here is a generic method that replaces all null pointers it can find in an object with its scalar default values, fills String fields with an empty string and does so recursively if the objects it finds have a parameterless default constructor. Hope this helps other people in the same situation as well.
static void fillNullObjects(Object object) {
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true);
if (field.get(object) != null) {
continue;
}
else if (field.getType().equals(Integer.class)) {
field.set(object, 0);
}
else if (field.getType().equals(String.class)) {
field.set(object, "");
}
else if (field.getType().equals(Boolean.class)){
field.set(object, false);
}
else if (field.getType().equals(Character.class)) {
field.set(object, '\u0000');
}
else if (field.getType().equals(Byte.class)) {
field.set(object, (byte) 0);
}
else if (field.getType().equals(Float.class)) {
field.set(object, 0.0f);
}
else if (field.getType().equals(Double.class)) {
field.set(object, 0.0d);
}
else if (field.getType().equals(Short.class)) {
field.set(object, (short) 0);
}
else if (field.getType().equals(Long.class)) {
field.set(object, 0L);
}
else if (field.getType().getDeclaredFields().length > 0){
for (Constructor<?> constructor : field.getClass().getConstructors()) {
if (constructor.getParameterTypes().length == 0) {
field.set(object, constructor.newInstance());
fillNullObjects(field.get(object));
}
}
}
} catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
Check out Apache Commons' StringUtils
StringUtils.defaultString(yourString)
This replaces nulls with an empty String. Or you can define your own replacement:
StringUtils.defaultString(null, "foo") // returns "foo"
http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#defaultString(java.lang.String)
Store your variables in an array (or list, if you don't know exacty the number of variables but I don't think so) and loop over it
String[] variables;
//...
for(int i = 0; i < variables.length; i++)
if(variables[i] == null) variables[i] = "";
20 field variables sounds like an egregious case. You should try to avoid explicitly handling that many variables in any situation, or at least factor the code so they are only ever explicitly listed in one place.
A common pattern is to associate each variable with an enumeration, and use the enumeration as a key in a Map with type Enum -> String, or use the enumeration's ordinal as an index into a String array that is sized to the Enumeration value.
Like so:
public enum StringProperties {
TTL, RECVBUF, SENDBUF, RETRIES, ... ;
}
If you wanted explicit default values, you can couple an enumeration with a number of parameters:
public enum StringProperties {
TTL ("100"),
RECVBUF ("1024"),
SENDBUF ("1500"),
RETRIES ("10"),
...
;
public String getDefaultValue() { ... }
}
This strategy means that your code needs minimal modification if you need to add/remove a property, or change a default value.
In your (copy constructor?) case, you can loop over the enumeration values with something like:
for (StringProperties property : StringProperties.values()) {
if (obj.getProperty(property) != null) {
// handle present case
...
} else {
// handle default storage case
...
}
}
Or, like thomas said, you can use a String array on its own, but this assumes that you don't need a way to address each String.
public static String checkNull (String inputString){
if(inputString == null){
inputString = "";
}
return inputString;
}
And just call that whenever you want to check a string.
For each field use the standard Java method:
Objects.toString(field, "");
Avoid constructor with a large number of fields if possible. Use Builder instead (as suggested in Effective Java, Item 2: Consider a builder when faced with many constructor parameters).
I have an array of varying length, and I'd like to read from a fixed position. If the position is out of bounds, I'd like to read a null, instead of throwing. I can of course do something like
if(theArray.length <= colNum){ result = null; }
else{ result = theArray[colNum]; }
but that seems kind of inelegant. I'd like to be able to make a one-liner or simple function call that acts like theArray[colNum] except returns null instead of throwing an out-of-bounds exception. Is there something like that I'm overlooking? Am I overthinking this?
You can use the ternary operator.
Here is a one-liner:
result = ((colNum > theArray.length - 1) || (colNum < 0)) ? null : theArray[colNum];
Depends on what you think is more readable, but you can always use the raised exception:
public String read(String[] array, int index)
{
try
{
return array[index];
}
catch(IndexOutOfBoundsException e)
{
return null;
}
}
It depends, what "elegant" means to you?, There are several of ways for doing it, if you want short code, use the ternary operator:
result = theArray.length <= colNum ? null : theArray[colNum];
Also, you can do the read, and try/catch an ArrayIndexOutOfBoundsException:
try {
result = theArray[colNum];
} catch(ArrayIndexOutOfBoundsException e) {
result = null;
}
And you can encapsulate any of the both in a method, so your invoking code will look like:
result = readFromArray(theArray);
amountStr is a value that occasionally contains a double value represented as a string.
I want to use Double.parseDouble to read it into a double variable: amountDbl.
this.amountDbl = Double.parseDouble(amountStr);
It seems to throw a NullPointerException if amountStr doesn't have a value.
Does this mean I have to write a check like this every time?
if(amountStr!=null)
this.amountDbl = Double.parseDouble(amountStr);
Because I have so many statements like this in my code, I'm hoping for a more concise way of doing this check (or avoiding it).
You get a conciser expression if you use the ternary operator:
this.amountDbl = amountStr != null ? Double.parseDouble(amountStr) : 0;
or write your own utility function
public static double parseDoubleOrNull(String str) {
return str != null ? Double.parseDouble(str) : 0;
}
and do
this.ammountDbl = parseDoubleOrNull(ammountStr);
Note however that this doesn't protect you against malformed doubles. If this is a concern I suggest you go with the utility function and do something like this:
public static double parseDoubleSafely(String str) {
double result = 0;
try {
result = Double.parseDouble(str);
} catch (NullPointerException npe) {
} catch (NumberFormatException nfe) {
}
return result;
}
If you're after concise code you could even do
import static pkg.UtilClass.parseDoubleSafely;
Create a wrapper class for the amount that handles this test in the constructor/factory or handles a null amount as a special case, eg the Null option pattern
Use a Java utility library like guava that implements a Optional (expected to come in Guava r10)
Google Guava has a T firstNonNull(T first,T second) that can be used as Double.parseDouble( Objects.firstNonNull(amountStr,"0") )
(Switch to Scala and use the Option Pattern)
Why not initialize it beforehand to a "default" value?
String amountStr = /* some default value */
Then, when you use the variable, check for that special case.
if (amountDbl != /* some default value */)
//parse it
You could always surround it with try/catch or use a ternary operator (as aioobe did)
try{
this.amountDbl = Double.parseDouble(amountStr);
} catch (Exception ex){
ex.printStackTrace();
}
It's not much better but you could do:
this.amountDbl = Double.parseDouble(amountStr==null ? "" : amountString);
Might be a couple of years late to answer this question. The NumberUtils Class in org.apache.commons.lang3.math package has a method createDouble that does what you are asking for(https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/math/NumberUtils.html#createDouble-java.lang.String-)
I was initializing an object and needed to convert from String to Double and ran in to null values from String.
A a = new A(value1, value2 == null ? null : Double.parseDouble(value2), value3....);
I use this:
Double.parseDouble(str.isEmpty()?"0":str);
or
Double.parseDouble((str==null||str.isEmpty())?"0":str);
I have a column in my database that is typed double and I want to read the value from it using a JDBC ResultSet, but it may be null. What is the best way of doing this? I can think of three options none of which seem very good.
Option 1: Bad because exception handling verbose and smelly
double d;
try {
d = rs.getDouble(1);
// do something
} catch(SQLException ex) {
if(rs.wasNull()) {
// do something else
} else {
throw ex;
}
}
Option 2: Bad because two fetches
s = rs.getString(1); // or getObject()
if(s == null) {
// do something else
} else {
double d = rs.getDouble(1);
// do something
}
Option 3: Bad because Java rather than SQL conversion
s = rs.getString(1); // or getObject()
if(s == null) {
// do something else
} else {
double d = Double.parseDouble(s);
// do something
}
Any suggestions on which way is better, or is there another superior way? And please don't say "Use Hibernate", I'm restricted to JDBC code only here.
Option 1 is closest:
double d = rs.getDouble(1);
if (rs.wasNull()) {
// do something
} else {
// use d
}
It's not very nice, but that's JDBC. If the column was null, the double value is considered "bad", so you should check using wasNull() every time you read a primitive that is nullable in the database.
Depending on your JDBC driver and database, you may be able to use a boxed type and cast:
Double doubleValueOrNull = (Double)rs.getObject(1); // or .getObject("columnName")
It will be null if the column was NULL.
Be careful to check this still works if you change database.
Use:
rs.getObject(1)==null?null:rs.getBigDecimal(1).doubleValue()
Or with java 8 you can do this:
Double dVal = Optional.ofNullable(resultSet.getBigDecimal("col_name"))
.map(BigDecimal::doubleValue).orElse(null));
Kotlin version to retrieve a nullable field:
val parentId = resultSet.getObject("parent_id") as Double?