Good Way to Encapsulate Integer.Parseint()

Good way to encapsulate Integer.parseInt()

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.

How can I efficiently (without throwing exceptions for invalid input) parse an integer in Java?

The best answer I have found so far without writing my own integer parsing code or using flaky regexes is to use Guava's Ints.tryParse(String string) or Longs.tryParse(String string, int radix) method.

Longs.tryParse() is basically a reimplementation of the standard Java Long.parseLong(), but returning null or a Long instead of throwing a NumberFormatException. This seems to me to be the best approach: it is as efficient at parsing as Long.parseLong() but handles the error case more efficiently.

How to get Integer#parseInt to return a value in case of overload

You could use BigInteger

BigInteger bi = new BigInteger("99999999999999999999999999");
BigInteger mv = new BigInteger(String.valueOf(Integer.MAX_VALUE));
System.out.println(bi.compareTo(mv));

if (bi.compareTo(mv) > 0)
return Integer.MAX_VALUE;
else
return bi.intValue();

Should one check if a string is empty before calling Integer.parseInt?

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.

How can I parse String to int with the default value?

You can try this method with a regular expression.

public static int parseWithDefault(String s, int defaultVal) {
return s.matches("-?\\d+") ? Integer.parseInt(s) : defaultVal;
}

Java - NumberFormatException when using .parseInt(String)

Your problem is that digits[a+1] hasn't been defined yet. I see that on line 2 you have

digits[a] = Character.toString(sq.charAt(a));

and you're iterating over a in a for loop, so I daresay that digits[a+1] hasn't been assigned yet.

UPDATE 1

Check out this solution, it shows how to properly catch that exception and how to avoid it:

Java: Good way to encapsulate Integer.parseInt()

UPDATE 2

I decided to add a fixed version of your code:

public static void main(String[] args) {
// TODO code application logic here
Scanner maxVal = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
System.out.println("enter the max value of ordered squares:");
int max = maxVal.nextInt();
for(int i = 0; i*i <= max; i++){
int L = String.valueOf(i*i).length();
String sq = String.valueOf(i*i);
String [] digits = new String[L];
for(int a = 0; a < L; a++){
digits [a] = Character.toString(sq.charAt(a));
if(L == 1 || a == 0){
System.out.print(sq + "");
}else if(Integer.parseInt(digits [a]) < Integer.parseInt(digits[a+1])){
System.out.print(sq);
}else{

}
}
}
}

While I don't know the utility of your code, but this implementation might be simpler:

public static void main(String[] args) {
// TODO code application logic here
Scanner maxVal = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
System.out.println("enter the max value of ordered squares:");
int max = maxVal.nextInt();

for(int i = 0; i*i <= max; i++){
long sq = i*i;
if(sq > 9){
String[] digits = sq.toString().split("");

//Notice that I start at index 1, so I can do [a-1] safely
for(int a = 1; a < digits.length; a++){
if(Integer.parseInt(digits [a-1]) < Integer.parseInt(digits[a])){
System.out.print(sq);
//I guess we don't want a number like 169 (13*13) to be displayed twice, so:
break;
}
}
} else {
System.out.print(sq);
}
}
}

String to Int in java - Likely bad data, need to avoid exceptions

That's pretty much it, although returning MIN_VALUE is kind of questionable, unless you're sure it's the right thing to use for what you're essentially using as an error code. At the very least I'd document the error code behavior, though.

Might also be useful (depending on the application) to log the bad input so you can trace.



Related Topics



Leave a reply



Submit