I have a variable of type String loanTerm and want to check whether it is within the range 1-999. It can contain NA or number from 1-999 (exclude decimal) and can't be blank. I have used #NotNull, #Range(min=1,max=999) but couldn't able to perform complete validation.
in pojo class use the following set method for loanTerm.
setloanTerm(String str){
if(str != null && str !=""&&Integer.parseInt(str) >=0 && Integer.parseInt(str)<=999){
loanTerm=str;
}
}
If you want to see if string within a range the simplest way is to use if statement with String.compareTo() method:
if(str.compareTo(lower) > 0 && upper.compareTo(str) < 0){
System.out.println("inside the range");
}
First, check it whether it is empty or not. Than you can use Integer class to check whether it can be cast to Integer or not.
Integer validateLoanTerm(String loanTerm) {
if(!StringUtils.isEmpty(loanTerm) && Integer.parseInt(loanTerm) > 0 && Integer.parseInt(loanTerm) < 999) {
return Integer.parseInt(loanTerm);
}
return null;
}
I used Integer value as return value of the method. However if you do not need the value of it, you can just return a boolean from the method.
Related
I need to know the "best" and safest way to get a value held within a Set if there is only one entry. methodToGetValues() is used extensively to read config files and return a list of values given a specific key, in this case "enabled". For the enabled key, there should only be one entry returned in the Set, obviously "true" or "false" but, mistakes happen. I have the following which seems a little convoluted:
Set<String> enabled = methodToGetValues("enabled");
if (!enabled.isEmpty() && enabled.size() < 2 && "true".equals(enabled.iterator().next())) {
...
}
Can anyone suggest a simpler yet still robust way of checking this?
Your question asks to get something from the Set. But your example just needs a check.
If you know what to expect in the Set, this works fine.
if (enabled != null && enabled.size() == 1 && enabled.contains("true")) {
...
}
Otherwise, if you just want to get the element but don't know what it is, the iterator you suggested works fine.
String getOnlyElement(Set<String> enabled, String default) {
return (enabled == null || enabled.size() != 1) ? default : enabled.iterator().next();
}
I like having null checks but it depends on what methodToGetValues returns.
Unsure of what the use case is that would drive using a Set<String> for this data but here is an option:
// check size = 1 over two checks, use contains rather than grabbing an iterator
if (set.size() == 1 && set.contains("true")) {
...
}
public Set<String> getValues(final String key){
.....
}
public String getValue(final String key) {
final Set<String> values = getValues(key);
if (values == null || values.size() != 1) {
throw new IllegalStateException("Invalid configuration for give key :" + key);
}
return values.iterator().next();
}
public Boolean getValueAsBoolean(final String key) {
return Boolean.valueOf(getValue(key));
}
You can modify method to have accept argument to return default value when keys are not found. You can add different methods to return specific type object like inte, boolean, this way code looks cleaner
I want to create a setter method for BigDecimal array but I can't get the right way of assigning a value for it. I want my array to contain at least a "zero" element or none for the mean time.
public void setAddends(BigDecimal addends[]){
addends[] = BigDecimal.ZERO;
}
BigDecimal addends[] = new BigDecimal [10];
...
public void setAddends(BigDecimal addends[]){
addends[0] = BigDecimal.ZERO;
}
If you want to put some constraints on the input parameter, you should require the caller of the method to provide a valid parameter instead of changing it inside the method. Consider throwing IllegalArgumentException if the parameter is invalid.
As far as I understood, you want the array to either contain at least one zero or contains nulls only:
public void setAddends(BigDecimal[] addends) {
if (numberOfNonNullsIn(addends) != 0 && numberOfZerosIn(addends) == 0) {
throw new IllegalArgumentException("addends should either contain at least one zero or contain nulls only");
}
// ...
}
private long numberOfZerosIn(BigDecimal[] addends) {
return Arrays.stream(addends).filter(a -> a != null && a.compareTo(BigDecimal.ZERO) == 0).count();
}
private long numberOfNonNullsIn(BigDecimal[] addends) {
return Arrays.stream(addends).filter(a -> a != null).count();
}
I need to see if a text field has an empty value. I need to see if
if(Double.parseDouble(distanceTf.getText())==0)
I know 0 won't work. I also know null won't work and I know .equals won't work.
Does anyone know how I can compare this line of code to a null value?
if (stageTf.getText().equals("") || Double.parseDouble(distanceTf.getText()) == null) {
JOptionPane.showMessageDialog(null, "You did not enter both a stage number and distance");
return;
}
Thanks for all the above replies but they don't work.
The part of the code I have trouble with is:
if (Double.parseDouble(distanceTf.getText())==null)
The rest of it is fine.
I have tried putting this outside the if statement and using distanceTf.getText().equals("")
in the if statement but this doesn't work either.
I just can't find out how to assign an empty value to the line of code for a double.
I know null, .equals or "" won't work.
You're not clear on which value could be null, so I'll assume both.
Since Double.parseDouble requires a non-null argument, you need to check it for null.
if(null != distanceTf.getText() && Double.parseDouble(distanceTf.getText()) != 0.0)
stageTf.getText() could return null too, but if you're guaranteed to be comparing a known non-null String against null, it would return false. So, this comparison is safer:
if("".equals(stageTf.getText())
The important thing to understand is: what you mean with null value? A null reference or an empty string?
You could do
stageTf.getText().isEmpty()
to check if the string is empty and parse it only if it contains something.
// here remember it's still wrong
if (!stageTf.getText().isEmpty() && Double.parseDouble(distanceTf.getText()) == null) {
Second problem: Double.parseDouble doesn't return null since it returns a native type.. it thrown an exception if something went wrong. So you can catch NumberFormatException.
Then you could write:
try {
double result;
if (!stageTf.getText().isEmpty() && (result = Double.parseDouble(distanceTf.getText()))) {
/* i think you need the result of the conversion, so i saved it in result */
}
}
catch (NumberFormatException e) { /* something went wrong! */ }
You need to test if the field is empty first. You did it correctly with your first conditional on the stageTf field. You need to do the same with the distanceTF field. This means nesting your conditional statements.
if(stageTF.getText().equals(""))
if(distanceTF.getText().equals("")){
/* ... */
} else {
//here it is safe to test for exceptions by using a try/catch
try{
//here you can parse the string to your Double
}catch(NumberFormatException nfe){ /* ... */ }
}
first of all you should check for null before empty because if the value is null you'll get a NullPointerException on the first one.
Second you'll get a NullPointerException if distanceTf.getText() is null on the Double.parseDouble
Double.parseDouble() doc
what I would do is create a method validate as follows:
private boolean validate(String field){ //where field = stageIf.getText() for example
if(field != null && field.trim().length() > 0)
return true;
else return false;
}
Parse outside if statment, then just compare :
if(distanceTf.getText() == "")
I have a List that contains many rows of data.What i want to do is return only the first iterated value and nothing else.
public int getnumber() {
for (Bike temp : bikes) {
return temp.getBikeID();
break;
}
}
I tried something like the above..but the break statement is unreachable. How may i achieve this ?
I know that i could still just declare a variable outside of the loop then assign the value in the loop but the returned value will be the last row.
This is because of the return statement before break. The return statement will take the execution to the calling method. so, the break statement is unreachable.
You don't need to iterate to get the first value of the collection. The first index would be 0. so, just make it
if(bikes!=null && bikes.size() > 0)
return bikes.get(0).getBikeId();
return -1; // `-1` denotes failure or put anything relevant to failure
Do not loop and try directly :
return bikes.get(0).getBikeId();
Try like this -
// null and size check to make sure if there is something on 0 index
return bikes != null && bikes.size > 0 ? bikes.get(0).getBikeId() : 0;
Simply delete the break statement. In fact, this is all you need:
for (Bike temp : bikes) return temp.getBikeID();
return -1;
In place of return -1 put the behavior you prefer for the "not found" case.
You can access you list's indices via .get() directly. No need for an iteration if you only need one or a hand full of specific elements:
public int getnumber() {
int result = 0;
if (bikes != null && bikes.size() > 0)
result = bikes.get(0).getBikeID();
return result;
}
Or even shorter, with the use of the ternary operator (condition ? true : false;):
public int getnumber() {
return (bikes != null && bikes.size() > 0) ? bikes.get(0).getBikeId() : 0;
}
I have written this function which will set
val=max or min (if val comes null)
or val=val (val comes as an Integer or "max" or "min")
while calling i am probably sending checkValue(val,"min") or checkValue(val,"max")
public String checkValue(String val,String valType)
{
System.out.println("outside if val="+val);
if(!val.equals("min") && !val.equals("max"))
{
System.out.println("Inside if val="+val);
try{
System.out.println("*Inside try val="+val);
Integer.parseInt(val);
}
catch(NumberFormatException nFE)
{
System.out.println("***In catch val="+val);
val=valType;
}
return val;
}
else
{
return val;
}
}
But the problem is if val comes null then
outside if******val=null
is shown.
Can any1 tell me is this a logical mistake?
And why will I correct?
If val is null, then the expression val.equals("min") will throw an exception.
You could correct this by using:
if (!"min".equals(val) && !"max".equals(val))
to let it go inside the if block... but I would personally handle it at the start of the method:
if (val == null) {
// Do whatever you want
}
Btw, for the sake of readability you might want to consider allowing a little more whitespace in your code... at the moment it's very dense, which makes it harder to read.
...the problem is if val comes null then outside if****val=null is shown. Can any1 tell me is this a logical mistake?
The output is correct; whether you want it to come out that way is up to you.
Your next line
if(!val.equals("min") && !val.equals("max")){
...will throw a NullPointerException because you're trying to dereference val, which is null. You'll want to add an explicit check for whether val is null:
if (val == null) {
// Do what you want to do when val == null
}
you should use valType instead of val to check either minimum or maximum is necessary to check.
My advice to you in such cases to use boolean value or enum instead of strings. Consider something like that:
/**
* check the value for minimum if min is true and for maximum otherwise
*/
public String checkValue(String val, boolean min){
if (min) {
// ...
} else {
// ...
}
}
If you need to compare strings against constants you should write it the other way around to make it null-safe:
if (! "min".equals(val))
And while this is mostly a style issue, I would make all method arguments final and not re-assign them (because that is confusing), and you can also return from within the method, not just at the end. Or if you want to return at the end, do it at the very end, not have the same return statement in both the if and the else branch.