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
}
Related
I use retrofit to implement an interface like this:
Observable<QueryResult> queryData(#Body QueryParams params);
and define the QueryResult class:
class QueryResult {
int count;
...
}
When I execute the queryData statement, it produces the following error:
com.google.gson.JsonSyntaxException: java.lang.NumberFormatException: Invalid double: ""
Apparently, it is caused by the api returning data something like this:
{"count":"",...}
The "count" is designed to represent a number, but somehow or maybe sometimes, the server developer wants to use "" to represent 0.
My question is how do I error handle this situation?
I have tried to do the error handling in the QueryResult class:
class QueryResult {
String count; // change from int to String;
...
int getCount() {
// do the error handling
int ret = 0;
try {
ret = Integer.parseInt(count);
} catch (Exception e) {}
return ret;
}
}
But is there a better way of handling it? Declaring the count to be a String seems not quite intuitive. I am supposing there could be an option to configure the retrofit.
Update
Thanks for the answers of suggestions for efficiency improvement and registering a TypeAdapter in the gson converter.
But what I want to know is if the error handle could be done by the retrofit library itself. The point of view is that when I originally declare the count field as int, it can handle both the integer and string type of value from server, like:
{"count":123,...} or {"count":"123",...}
without error. So I am assuming the error handle could be done together with the integer paring behavior in the library itself.
Thanks in advance.
First of all this inconsistent behaviour in API response is not feasible.
Retrofit won't be able to handle this situation.You have to manually handle this response as you have mentioned in the question.But you can do that in an efficient way like this
class QueryResult {
Object count; // change to Object;
int getCount() {
// do the error handling
if (count instanceof Integer) {
return ((Integer) count);
} else {
return 0;
}
}
}
Try to check that your count is empty or not before converting it to it
or better to change the response from backend
Try this
public class QueryResult {
String count;
int getCount() {
try {
if (!TextUtils.isEmpty(count)) {
return Integer.parseInt(count);
}
} catch (NumberFormatException e) {
}
return 0;
}
}
The sweetest way I can tell you is just parse double as way you do.
Double ans=Double.ParseDouble(yourstringvalue);
This gives ans as double.
The problem I get here is that you are receiving an empty string ""
Just put the condition on it as
Double ans=0.0
if(yourstringvalue!="" || yourstringvalue!=null){
// then parse here
ans=Double.ParseDouble(yourstringvalue);
}
You will get required value in ans
Proceed further as
if(ans!=0.0){
//do your task here
}
Just use Object instead of primitive datatypes. Instead of int use Integer object. The Integer class wraps a value of the primitive type int in an object. Object classes are available for all primitives datatypes in java
Retrofit return null if value is not found and primitives datatypes (int, double) cannot handle null value and give this error. Object classes of primitive datatypes can handle null values
In your case, this change may solve your issue if this count variable is cause of exception
class QueryResult {
Integer count;
...
}
but your exception say double. I think error is because of some variable which is of double datatype and get null value. Just change primitive double to Double object and It will solve your issue
Double var;
A part of a small program I am coding:
String maxs = "";
int maxi = 0;
At this part I defined two variables as int and String.
public Class(String max){
try {
this.maxi = Integer.parseInt(max);
}catch (Exception e){
this.maxs = max;
}
}
I think this way I will get to define one of both variables, if the String does not parse to int it will be saved as normal String.
Now I need to check what I need to return:
private TypeOfReturn getMax(){
if(this.maxi == 0){
// return maxs (return String)
} else if (this.maxs.equals("")) {
// return maxi (return int)
} else return null;
}
The quastion is, how do I fill the missing parts of the method getMax()?
Is it even possiable in Java?
Use Object instead of TypeOfReturn
You can change the TypeoOfReturn to Object and then return the respective types.
Another way to find out fast if a string is a number or not, which is the main part of your program, is to use the lambda expressions in java 8 like this:
String max = "123";
boolean isNumber = max.chars().allMatch(Character::isDigit);
System.out.println(isNumber);
Which will give you the output
true
Make your TypeOfReturn as String object type and convert the maxi as String and return that String in your else if condition.
Note: you cannot return both the int and String in the Same method.
I am searching for a method to check if it is possible to convert a string to int.
The following link says that it is not possible but since new Java version are available I would like to check.
You may wish to consider the NumberUtils.isDigits method from Apache Commons. It gives a boolean answer to the question and is null safe.
For a broader range of numbers that could include decimal points such as float or double, use NumberUtils.isParsable.
It is not a good idea to use exceptions to control flow - they should only be used as exceptions.
This is a classic problem with a regex solution:
class ValidNumber {
// Various simple regexes.
// Signed decimal.
public static final String Numeric = "-?\\d*(.\\d+)?";
// Signed integer.
public static final String Integer = "-?\\d*";
// Unsigned integer.
public static final String PositiveInteger = "\\d*";
// The valid pattern.
final Pattern valid;
public ValidNumber(String validRegex) {
this.valid = Pattern.compile(validRegex);
}
public boolean isValid(String str) {
return valid.matcher(str).matches();
}
}
Java 8 does not change anything by the type parsing. So you still have write your own typeParser like this:
public Integer tryParse(String str) {
Integer retVal;
try {
retVal = Integer.parseInt(str);
} catch (NumberFormatException nfe) {
retVal = 0; // or null if that is your preference
}
return retVal;
}
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;
}
}
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);
}