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.
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.
Videos
public static boolean isParsable(String input) {
try {
Integer.parseInt(input);
return true;
} catch (final NumberFormatException e) {
return false;
}
}
Check if it is integer parseable
public boolean isInteger(String string) {
try {
Integer.valueOf(string);
return true;
} catch (NumberFormatException e) {
return false;
}
}
or use Scanner
Scanner scanner = new Scanner("Test string: 12.3 dog 12345 cat 1.2E-3");
while (scanner.hasNext()) {
if (scanner.hasNextDouble()) {
Double doubleValue = scanner.nextDouble();
} else {
String stringValue = scanner.next();
}
}
or use Regular Expression like
private static Pattern doublePattern = Pattern.compile("-?\\d+(\\.\\d*)?");
public boolean isDouble(String string) {
return doublePattern.matcher(string).matches();
}
Here is the regular code to use Interger.parseInt():
try {
Integer.parseInt(string);
} catch (NumberFormatException e) {
//code
}
But you could use the following (it catches all exceptions):
try {
Integer.parseInt(string);
} catch (Exception e) {
//code
}
Is that your question?
It is not true that we do not need to check for NumberFormatExceptions.
A checked exception is an exception that could be thrown by a method you're calling and that you're checking for it and handling it appropriately. In the example you're giving, on NumberFormatException you might want to let the user know that they provided an invalid number.
Basically all exceptions should be checked and handled.
Hey guys so I am trying to parse integer from a string in the following function and I get the following error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "9876543210" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:583) at java.lang.Integer.parseInt(Integer.java:615) at Solution.plusOne(Solution.java:129) at Solution.main(Solution.java:149)
Here is my following code:
public static int[] plusOne(int[] digits)
{
StringBuilder str = new StringBuilder();
for(int c:digits)
{
str.append(c);
}
String num = str.toString().trim();
System.out.println(num);
int sum = Integer.valueOf(num)+1; //I have used Integer.parseInt(num) also
String temp = ""+sum;
int[] total = new int[temp.length()];
for(int i=0;i<temp.length();i++)
{
total[i]=Character.getNumericValue(temp.charAt(i));
}
return total;
}
public static void main(String[] args)
{
int[] arr = {9,8,7,6,5,4,3,2,1,0};
System.out.println(plusOne(arr));
}I am curious where I am going wrong here since I am pretty sure my string sum does not have any spaces or characters. Any help would be appreciated!
Because the result will get greater than Integer.MAX_VALUE
Try this
System.out.println(Integer.parseInt("yellow", 35));
System.out.println(Long.parseLong("howareyou", 35));
and for
Long.parseLong("abcdefghijklmno",25)
you need BigInteger
Try this and you will see why
System.out.println(Long.MAX_VALUE);
System.out.println(new BigInteger("abcdefghijklmno",25));
Could it be that the number is > Integer.MAX_VALUE? If I try your code with Long instead, it works.