Yes, but: Wrap it in a thin method (and eliminate the redundant else), or use an existing implementation, like Commons Lang's NumberUtils.toInt(str, defaultValue):
NumberUtils.toInt(myString, 0);
This method handles null values and conversion failures.
Writing the same thing on your own is straight-forward:
- Check for null, and/or...
- ...Wrap the
NumberFormatExtensionexception
Yes, but: Wrap it in a thin method (and eliminate the redundant else), or use an existing implementation, like Commons Lang's NumberUtils.toInt(str, defaultValue):
NumberUtils.toInt(myString, 0);
This method handles null values and conversion failures.
Writing the same thing on your own is straight-forward:
- Check for null, and/or...
- ...Wrap the
NumberFormatExtensionexception
Well, you could use the conditional operator instead:
return StringUtils.isNotBlank(myString) ? Integer.parseInt(myString) : 0;
If you need to do this in multiple places, you'd probably want to put this into a separate method. Note that you should also consider situations where myString is null, or contains non-numeric text.
Don't use == or != to compare strings in Java - it only compares the references, not the contents of the strings. Also, I doubt that toString would ever return null. I suspect you want:
Foo x = jsonArray.getJSONObject(i).get("SECNO");
if (x != null && x.toString().trim().length() > 0)
(I don't know what the type of jsonArray.getJSONObject(i).get("SECNO") would be, hence the Foo.)
In this particular case I've used length() > 0 to detect a non-empty string - but for more general equality, you'd want to use equals, so an alternative is:
if (x != null && !x.toString().trim().equals(""))
Why not just,
int appointment.mSecNo = -1;
try {
appointment.mSecNo = Integer.parseInt(jsonArray.getJSONObject(i).get("SECNO").toString());
}catch(Exception e) {
log.error(" your error message ");
}
You cannot cast from String to Integer. However, if you are trying to convert string into integer and if you have to provide an implementation for handling null Strings, take a look at this code snippet:
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;
}
If you're using apache commons, there is an helper method that does the trick:
NumberUtils.createInteger(myString)
As said in the documentation:
"convert a String to a Integer, handling hex and octal notations; returns null if the string is null; throws NumberFormatException if the value cannot be converted.
This line is throwing the NumberFormatException:
Integer.parseInt(houredit.getText().toString());
Because houredit.getText().toString() return an empty string and you can't parse empty String into Integer.
Before you parse check that the houredit.getText().toString() don't return with empty string.
I know this is an old question, but the current answers didn't seem to have multiple answers or examples of how to fix it. The reason why you are getting this is because it is getting a NumberFormatException and because the string is empty it can't parse it and crashes, so there are two ways you can fix it.
The first way would be to check to see if the string is empty and if not then follow through with the parsing of the data.
if (!houredit.getText().toString().trim().equals("")){
int hour = Integer.parseInt(houredit.getText().toString());
int minute = Integer.parseInt(minuteedit.getText().toString());
Intent intent = new Intent(AlarmClock.ACTION_SET_ALARM);
intent.putExtra(AlarmClock.EXTRA_HOUR, hour);
intent.putExtra(AlarmClock.EXTRA_MINUTES, minute);
if (hour <= 24 && minute <= 60) {
startActivity(intent);
}
}
The second way would be with a try/catch, which tells the app to try something and if it can't do it throw an error.
try{
int hour = Integer.parseInt(houredit.getText().toString());
int minute = Integer.parseInt(minuteedit.getText().toString());
Intent intent = new Intent(AlarmClock.ACTION_SET_ALARM);
intent.putExtra(AlarmClock.EXTRA_HOUR, hour);
intent.putExtra(AlarmClock.EXTRA_MINUTES, minute);
if (hour <= 24 && minute <= 60) {
startActivity(intent);
}
}catch(Exception ignored){} // <- capture exception if you need, else you can ignore it
here is a solution :
int tryParseInt(String value) {
try {
return Integer.parseInt(value);
} catch(NumberFormatException nfe) {
// Log exception.
return 0;
}
}
you should catch NumberFormatException instead of exception.
I'd consider using NumberUtils.toInt from Apache Commons Lang which does exactly this:
public static int NumberUtils.toInt(java.lang.String str, int defaultValue)
The implementation uses the already mentioned Integer.parseInt with an additional null check.
See also: Effective Java, 2nd edition, Item 47: Know and use the libraries (The author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.)
Use this instead:
int stringNumber = nums.length() > 0 ? Integer.parseInt(nums) : 0;
This will parse the number if its length is not zero, otherwise it will set stringNumber to the value 0. Change it if you want a different value for an empty string.
This will still fail if the string between the delimiters is not a valid number. If that is a possibility:
int stringNumber = 0;
try {
stringNumber = Integer.parseInt(nums);
}
catch (NumberFormatException nx)
// depends on how you want to handle invalid numbers
}
Java ternary operator can be used nicely as below:
int stringNumber = (!nums.isEmpty() ?Integer.parseInt(nums):0);
You have at least one empty cell in your table.
Here's a suggestion:
try {
sum += Integer.parseInt(columnValue);
} catch (NumberFormatException nfe) {
// the cell is either empty or not an integer number
// will be treated as zero (0)
}
Note, that the method getColumnValue(int i, String name) is not defined for javax.swing.JTable. If you use a subclass of JTable then the error could be in that class/method too: it may return an empty string instead of a cell value.
I guess you will need to convert an empty String or null value to zero.
So you need to trim the whitespaces when you get the String value and then check if the string is empty.
Here is what your code should look like
final ArrayList<String>ValuesList = new ArrayList<String>();
final int nb = myTable.getRowCount();
int sum=0;
String columnValue = "";
for (int i = 1; i < nb; i++)
{
columnValue = myTable.getColumnValue(i, columnName).trim();
if (!columnValue.isEmpty()) {
sum=sum+Integer.parseInt(columnValue);
}
ValuesList.add(columnValue);
}
If empty strings are exceptions (i.e. it should not happen) in your data then it is accepted practice to not check them and just let the exception system handle it.
If empty strings are possible (even if rare) and would mean something (e.g. "" -> "0") then you should check.
The bottom line is you should not use exceptions to control program flow.
No.
You have to catch the NumberFormatException anyway, so adding an additional check just adds more code a reader has to wade through for no functional benefit.
(I'm assuming from the question you do want to check if it's invalid in any case, and not just check if its empty. If you just want to check whether it's empty and not whether it's generally invalid, then obviously just use isEmpty() and don't catch anything at all!)
Yes, exceptions should not normally be used for control flow - but catching a NumberFormatException to check if a String is a valid int or not is a reasonably well understood exception to this rule.
You could return an Integer instead of an int, returning null on parse failure.
It's a shame Java doesn't provide a way of doing this without there being an exception thrown internally though - you can hide the exception (by catching it and returning null), but it could still be a performance issue if you're parsing hundreds of thousands of bits of user-provided data.
EDIT: Code for such a method:
public static Integer tryParse(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
return null;
}
}
Note that I'm not sure off the top of my head what this will do if text is null. You should consider that - if it represents a bug (i.e. your code may well pass an invalid value, but should never pass null) then throwing an exception is appropriate; if it doesn't represent a bug then you should probably just return null as you would for any other invalid value.
Originally this answer used the new Integer(String) constructor; it now uses Integer.parseInt and a boxing operation; in this way small values will end up being boxed to cached Integer objects, making it more efficient in those situations.
What behaviour do you expect when it's not a number?
If, for example, you often have a default value to use when the input is not a number, then a method such as this could be useful:
public static int parseWithDefault(String number, int defaultVal) {
try {
return Integer.parseInt(number);
} catch (NumberFormatException e) {
return defaultVal;
}
}
Similar methods can be written for different default behaviour when the input can't be parsed.
An empty string doesn't represent any integer, so at face value your question has a trivial answer - do not convert an empty string to a valid integer.
The question behind the question seems to be "how to design a robust non-surprising string-to-int conversion utility". This is tricky - consider the following additional cases:
- What string number representations will you accept? There is more than decimal - the following strings are also integer number representations in common use: 0x0A, 2x10^2, 10E5, 08,...
- Will you consider converting strings representing floating point numbers to integer numbers?
- If you answer yes to the previous question, what rounding or truncation will you use?
- What about rational numbers?
- You can probably come up with a few more if you tried.
So all in all the actual answer to your question should be to use the string-to-number conversion library functions supplied with your current language and framework, if they have any. If there are no implementations for your situation, then look at other languages or libraries for inspiration of how to handle those cases in your own implementation. If you document what your conversion function does, then it will not (or at least should not) surprise the clients of your function.
If you're converting string to int similar to JavaScript's parseInt function, then you would probably want to have '' return NaN or throw an exception, as you said.
JavaScript returns NaN, but if your language doesn't have that convention or feature you should throw an exception or return a null value.