This question already has answers here:
Determine if object is integer
(3 answers)
Closed 6 years ago.
I'm using some API by restTemplate. The API returns a key whose type is integer.
But I'm not sure of that value, so I want to check whether the key is really an integer or not.
I think it might be a string.
What is the best way of checking if the value is really integer?
added:
I mean that some API might return value like below.
{id : 10} or {id : "10"}
If what you receive is a String, you can try to parse it into an integer, if it fails, it's because it was not an integer after all. Something like this:
public static boolean isInteger(String str) {
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException nfe) {
return false;
}
}
Object x = someApi();
if (x instanceof Integer)
Note that if someApi() returns type Integer the only possibilities of something returned are:
an Integer
null
In which case you can:
if (x == null) {
// not an Integer
} else {
// yes an Integer
}
One possibility is to use Integer.valueOf(String)
Assuming your API return value can either be an Integer or String you can do something like this:
Integer getValue(Object valueFromAPI){
return (valueFromAPI != null ? Integer.valueOf(valueFromAPI.toString()) : null);
}
Related
I want to create validator for input filed in order to check values and send error message if the inserted value is not int.
bean:
public class PricingCalculatorValidator implements Validator
{
#Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException
{
// Cast the value of the entered input to String.
String input = (String) value;
// Check if they both are filled in.
if (input == null || input.isEmpty())
{
return; // Let required="true" do its job.
}
// Compare the input with the confirm input.
if (containsDigit(input))
{
throw new ValidatorException(new FacesMessage("Value is not number."));
}
}
public final boolean containsDigit(String s)
{
boolean containsDigit = false;
if (s != null && !s.isEmpty())
{
for (char c : s.toCharArray())
{
if (containsDigit = Character.isDigit(c))
{
break;
}
}
}
return containsDigit;
}
}
What is the proper way to cast the inserted value? Now I get exception
serverError: class java.lang.ClassCastException java.lang.Integer cannot be cast to java.lang.String
As per the exception, JSF is actually passing an Integer instance as value to the validate() method. Technically, you should be casting it to Integer as below to keep the Java runtime happy.
// Cast the value of the entered input to Integer.
Integer input = (Integer) value;
Apparently you already bound the input field to an Integer property in the model like so:
<h:inputText value="#{bean.pricing}" />
private Integer pricing;
In other words, the whole custom validator is unnecessary. There's no point of validating if the value is an integer if it's already an Integer in first place. It can impossibly contain a non-digit as value.
Just get rid of that custom validator altogether.
JSF has several builtin converters for standard types like Integer which run automatically depending on the model value type. And, converters run right before validators. That's why the value already arrives as Integer in your custom validator. The only thing which seems relevant in your custom validator is the error message which is different from the standard conversion error message. In case you merely wanted to customize the conversion error message on the specific input field, just set it as converterMessage attribute on the input field.
<h:inputText value="#{bean.pricing}" converterMessage="Value is not numeric." />
Unrelated to the concrete problem, "validating" if the value represents a valid Integer or not (this process is in JSF actually called conversion and is supposed to take place in a custom converter) can be performed in a much simpler way:
String string = getItSomehowWithoutClassCastException();
try {
Integer integer = Integer.valueOf(string);
} catch (NumberFormatException e) {
throw new ConverterException(new FacesMessage("Value is not an integer."));
}
No need to inspect every single digit if you ultimately want to get an Integer. As said, the JSF builtin converter already takes care of this.
You don't have to verify each character.
Just perform:
boolean isDigit = true;
try {
new Integer(input).intValue();
} catch (NumberFormatException nfe) {
isDigit = false;
}
If any of the chars in input is not a number, the catch block will be executed, otherwise, that block will be skipped.
At the end, isDigit tells you whether input is an integer or not.
Note, if your input has too many digits to be an integer, it will also tell you that input is not an integer, even if every single character is a digit.
So this is basically what I want my code to say, as to avoid compile error's in the event that the user selects "Tea" instead of using the corresponding integer.
if(appSelection < 1 || appSelection > appetizersArray.length || appSelection != int)
the first two conditions are obviously to catch data that would be out of bounds, but I'm looking for a way to specify that the input needs to be an int.
If the only option is try catch just say so but I'm hoping there's a more elegant solution.
You could use a regular expression. The lower case \\d matches digits and adding a plus means consecutive. So,
String regex = "\\d+";
String[] arr = { "Tea", "123" };
for (String str : arr) {
if (str.matches(regex)) {
System.out.printf("%s is all digits%n", str);
} else {
System.out.printf("%s is NOT all digits%n", str);
}
}
Output is
Tea is NOT all digits
123 is all digits
Is this command-line input? If so, you can use the Scanner class's nextInt method (https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt%28%29). If it's coming from a web form, either your library should convert the value to an integer, in which case you already know it's an integer, or it's a string and you can call Integer.parseInt(String). Documentation here: https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt%28java.lang.String%29
Assuming that the data comes in a String, well, a try/catch is the thing to use, or some function to check if the provided data is a valid integer, like this:
boolean isValidInt(String s) {
try {
Integer.parseInt(s);
} catch (Exception e) {
return false;
}
return true;
}
Then you can say:
if(!isValidInt(appSelection)) someError();
Hope it helps!
Assuming this is a Java-related question, int is a primitive. The operation you are referring to has a operator: instanceof. Unfortunately, it does not work for primitive data types. In order to use this you have to use a wrapper class (i.e Integer). So:
int x = 1;
if (x instanceof Integer) { // compilation error }
Unfortunately, autoboxing does not work for this. What you can do is the following:
String value = ???; // ??? represents some unknown string value.
Later on, you can try to convert that String value to an Integer value:
try
{
Integer x = new Integer(str);
}
catch (NumberFormatException e)
{
// The exception will be thrown if the string does not represent a numeric value. For example: a34bc
}
If the instantiation of variable x succeeds, it will hold a numeric value. Because of Java unboxing mechanism, you will be able to pass 'x' to some method that takes a primitive int. For example:
try
{
Integer x = new Integer(str);
int result = addThisValue(x);
}
catch (NumberFormatException e) {// Do something }
...
public int addThisValue(int value) {...}
You will be able to pass variable x to that method safely.
I am using the following method to parse some text on the page
getNumberText().getText()
and want to do a assert/comparison using greaterThanOrEqualTo
So How do I convert the getText() result to integer value for comparison?
You could do the following, from this:
getNumberText().getText()
... create as one of answers was another method, which will return desired object in Your case int:
public int getNumber(){
return Integer.parseInt(getNumberText().getText());
}
so usage would be:
Assert.assertTrue(getNumber(), intNumber);
Hope this helps,
You need to Integer class to do this. Integer.parseInt(yourStringNumber). If the value is double then Double.parseInt(yourStringDouble).
int number = Integer.parseInt(getNumberText().getText());
In case that String is not parseable (thus not integer), NumberFormatException is thrown.
public int getNumberText(elem)
{
return int.Parse(elem.Text());
}
element = driver.FindElement(By.Id("something"));
actual_result = getNumberText(element)
if (actual_result == expected_result)
{
// do something
}
If I want to write a function that takes a string and converts it into an integer and I don't trust my input at all, what should I return if the string is invalid. I want to return 0 but would that be confusing since the number might actually be 0? Assume this is for an interview question and you need to check all edge cases.
In Java, it would be conventional to throw an Exception. This is what Integer.parseInt() does, which is the official Java implementation of this functionality.
what should I return if the string is invalid
Throw a RunTimeException. API already does that for you.If your try to parse an invalid string using Integer.parseInt(str) it would throw NumberFormatException at run time.
One possible option is to return default value if string can't be converted to integer. For example:
public int convert(String input, int defaultValue) {
try {
return Integer.parseInt(input);
} catch (Exception e) {
return defaultValue;
}
}
I am parsing XML files and I have several methods similar to:
public static Integer getInteger(Object integer) {
if (integer == null) {
return 0;
}
try {
return Integer.parseInt(integer.toString(), 10);
} catch (Exception ex) {
return 0;
}
}
So basically, you pass an object in with the assumption of converting it to an Integer (I also have versions for Float, etc).
This seems to work well but being a Java newbie, I was wondering how you would improve it. I am especially interesting in the boxing/unboxing aspect (at least, from a C# developer's perspective).
Thanks
EDIT
Sorry, I wasn't clear to what goes into the method. Yes, it's for an XML file now so it's always a string. But the string could be empty or maybe even null. I guess I wanted to always return a 0 if there was an error of any kind.
You shouldn't generally catch Exception. Catching NumberFormatException would be more appropriate here.
Any reason for converting to Integer instead of int? Why not let the caller perform the boxing conversion if they need it?
You don't say whether integer is an instance of Integer or not. If it is you can just cast it:
Integer i = (Integer) integer;
having checked for null and instanceof first.
If it is not an instance of Integer then what you're doing seems reasonable, although you only need to catch a NumberFormatException.
You should use instanceof operator, then make safe casting (so if Object integer is instanceof Integer, cast it).
Then you don't have to catch Exception (which in this case is unchecked NumberFormatException)
public static Integer getInteger(Object integer) {
if (integer == null) {
return 0;
}
if (integer instanceof Integer) {
return (Integer)integer;
}
return 0;
}
EDIT
If data is coming from XML, then it will of course never be Integer :) Then parsing from String is required still, so see other answers.
As Jon hinted, returning int (the primitive data type) instead of Integer (the wrapper class) would probably be better (assuming you never want to return null).
Also, adding this code could be a shortcut, when the input is often an Integer object or other Number subclass (I'm calling the input input because it's too confusing otherwise):
if (input instanceof Number) {
return ((Number) integer).intValue();
}
Returning Integer makes sense if you want to signal, that a value is empty. You're testing that already but you shouldn't return 0, unless you have a very clear and somewhat special requirement to do so. No value is not equal to 0.
Also, you can add more special cases besides null, like check for empty string:
public static Integer getInteger(Object integer) {
if (integer == null) {
return 0;
}
try {
String s = integer.toString();
if (s.isEmpty())
return 0;
return Integer.parseInt(s, 10);
} catch (Exception ex) {
return 0;
}
}
On the other side, you can cut all special cases, and go with only:
public static Integer getInteger(Object integer) {
try {
return Integer.parseInt(integer.toString(), 10);
} catch (Exception ex) {
return 0;
}
}
In the end, performance gains (or losses) depends on what portion of your input data is null, empty, unparsable integers, or "normal" integer strings.