I need to set boolean value only when all the conditions are set. I am struggling to set the boolean value inside the for loop. As per my code the value is set TRUE/FALSE based on last item in the list. But the value should set only when all conditions are set. Could someone help me on this?
boolean validateName(List<String> NameList, Name name) {
boolean value = false;
for (String name : NameList) {
name.hasName(name);
value = true;
}
return value;
}
Try this:
boolean validateName(List<String> nameList, Name name) {
for (String nameTmp : nameList) {
if(!nameTmp.equals(name))
return false;
}
return true;
}
Return false as soon as one condition is not met.
boolean validateName(List<String> NameList, Name aName) {
boolean value = false;
for (String name : NameList) {
if(!aName.hasName(name))
return false;
}
return true;
}
Try this if you are using Java 8:
return NameList.stream().allMatch(element -> element.equals(name))
Related
I need to test a dynamic Web Element using Selenium that will change its value after some time(back-end dependent). So, I built a boolean method that returns true if the web element has the value I need and false if that value is never retrieved. I want to check for value change at some intervals (thus, the Thread.sleep between page refreshes). My code always returns true, what am I doing wrong?
public boolean checkStatus() throws InterruptedException {
for(int i=0; i<2;) {
if (!serviceStatus.serviceElement().equals("LIVE")) {
Thread.sleep(5000);
theBrowser.navigate().refresh();
i++;
}else{
return true;
}
}
return false;
}
The method is used in the main test on the following assert:
Ensure.that(checkStatus()).isTrue();
I presume serviceElement() is the Webelement,you have to get the text for the element using getText() method and compare with the string you desire("LIVE") in this scenario.You seems to be comparing an Webelement with String here. Below should work if i understood the requirement correctly.
public boolean checkStatus() throws InterruptedException {
boolean isMatching = false;
for(int i=0; i<2;) {
if (!serviceStatus.serviceElement().getText().equals("LIVE")) {
Thread.sleep(5000);
theBrowser.navigate().refresh();
i++;
isMatching = false;
break;
}else{
isMatching = true;
}
}
return isMatching;
}
Hello I am very new to Java, I wanted to know if it were possible to pass a character to a method, and then return true if this character is valid.
I have this method:
public void btnColor(char c) {
if (hm.getHiddenWordUpdated().contains(String.valueOf(c))) {
// Change button color
}
}
What I would like is to have something like this, although it won't let me do this:
public boolean btnColor(char c, boolean b) {
if (hm.getHiddenWordUpdated().contains(String.valueOf(c))) {
return true;
}
}
So it takes a character variable c and returns true if valid. Is there a best practice for this sort of thing?
You can do something like this in order to always return some value. This should be possible and acceptable with Java.
public boolean btnColor(char c, boolean b) {
if (hm.getHiddenWordUpdated().contains(String.valueOf(c))) {
return true; // this will return in case of your condition is true
}
return false; // this will return otherwise.
}
try this single line
public boolean btnColor(char c, boolean b) {
return hm.getHiddenWordUpdated().contains(String.valueOf(c));
}
It'll return true or false.
When you have public boolean methodName, it means it MUST return a boolean. Having an "IF" statement in your code, means it can split up to a two possible ways: IF-true and IF-false. You have declared the true statement:
if (hm.getHiddenWordUpdated().contains(String.valueOf(c))) {
return true;
So you are covering 1/2 of the solution. But what if it is false ? Nothing ? This is why you have problems, so to solve your problem you code should looks like this:
public boolean btnColor(char c) {
if (hm.getHiddenWordUpdated().contains(String.valueOf(c))) {
return true;
} else {
return false;
}
Now if it is containing the character - it returns TRUE, but if it is not containing it returns FALSE.
All code paths need to return a value.
public boolean btnColor(char c, boolean b) {
if (hm.getHiddenWordUpdated().contains(String.valueOf(c))) {
// add additional code
return true;
}
return false;
}
Alternatively, you could use conditionals in a single line:
public boolean btnColor(char c) {
return (hm.getHiddenWordUpdated().contains(String.valueOf(c))) ? true:false;
}
I have a class like this:
public static class TiposDeHistorial
{
String CODIGO, TIPO;
public TiposDeHistorial()
{
}
public String getCODIGO()
{
return CODIGO;
}
public void setCODIGO(String CODIGO)
{
this.CODIGO = CODIGO;
}
public String getTIPO()
{
return TIPO;
}
public void setTIPO(String TIPO)
{
this.TIPO = TIPO;
}
}
and a list of it:
ArrayList<TiposDeHistorial> tiposHistorial;
So my question is: can I use tiposHistorial.contains(...) to search in a specific array field, CODIGO or TIPO, for example?
First of, you do not have an array but an ArrayList.
The contains method on a List operates with the equals method of it's stored elements (TiposDeHistorial in your case). Therefore the answer to your question is no.
Trying something like tiposHistorial.contains("a") will not work as there is a type mismatch: your list is of type TiposDeHistorial while you try to check for an element of String.
If you are using Java 8 you can use following code:
tiposHistorial.stream()
.filter(x -> "specific value for CODIGO".equals(x.getCODIGO()))
.findFirst()
.orElse(null);
It will return TiposDeHistorial object in the list containing specific CODIGO value or null otherwise.
As for your question: "contains" method just returns "true" or "false", not an object. Moreover it uses "equals" method of your object, so it will not help if you want to search using fields.
Contains method will return true only if your object equals with ur list elements objects.
You can try extending equals method and have your own criteria which can work for either CODIGO or TIPO.
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
test other = (test) obj;
if (CODIGO == null) {
if (other.CODIGO != null)
return false;
} else if (!CODIGO.equals(other.CODIGO))
return false;
return true;
}
The answers already given here are all correct, just if You don't know java streams, and would like to check if the list contains both some CODIGO and TIPO fields, for me the simplest solution would be:
ArrayList<TiposDeHistorial> tiposHistorial = new ArrayList<>();
//add elements to the list
String tipo = "TIPO"; // the TIPO value You are looking for in the list
String codigo = "CODIGO"; // the CODIGO value You are looking for in the list
boolean containsTipo = false;
boolean containsCodigo = false;
for (TiposDeHistorial element: tiposHistorial) {
if (!containsTipo && element.getTIPO().equals(tipo)) {
containsTipo = true;
}
if (!containsCodigo && element.getCODIGO().equals(codigo) ){
containsCodigo = true;
}
if (containsTipo && containsCodigo)
break;
}
By editing it just a bit, You may also find which elements of the array contain the values You are looking for, if that will be Your intention
I am newbie in java.
Here is my code:
public boolean endsLy(String str) {
if(str.length()>=2){
if(str.substring(str.length()-2).equals("ly")) return true;
}
else return false;
}
but compiler gives:
Error: public boolean endsLy(String str) {
This method must return a result of type boolean
Possible problem: the if-statement structure may theoretically
allow a run to reach the end of the method without calling return.
Consider adding a last line in the method return some_value;
so a value is always returned.
You are not handling the branch where (str.length()>=2, but !str.substring(str.length()-2).equals("ly"). Remove the else from the final return statement:
public boolean endsLy(String str) {
if(str.length()>=2){
if(str.substring(str.length()-2).equals("ly")) return true;
}
return false;
}
An even simpler alternative (also less prone to the kind of error you are having), is to have only a single return statement:
public boolean endsLy(String str) {
return str.length()>=2 && str.substring(str.length()-2).equals("ly");
}
Or simply :
public static boolean endsLy(String str) {
return str.length()>= 2 && str.substring(str.length()-2).equals("ly");
}
You might also check if the String is not null.
return str != null && str.length()>= 2 && str.substring(str.length()-2).equals("ly");
here a correction:
public boolean endsLy(String str) {
if(str.length()>=2){
if(str.substring(str.length()-2).equals("ly"))
return true;
else
return false;
}
else{
return false;
}
}
This error means that there might be a possibility that the function will not return anything under some circumstances.
so if this condition => if(str.length()>=2) stands true the code will enter into it. Now if this condition is false => if(str.substring(str.length()-2) the function will have nothing to return. So this is a wise thing that the error prompted.
This means that not all conditions in this function return a bool value. There is a chance that conditions may occur when function does not have anything to return.
because you do not have a boolean value is returned in case !str.substring (str.length () -2). equals ("ly")
if you want to check that your chain is composed of four characters in the last two are "ly" you can use the following codes:
public boolean endsLy(String str) {
if (str.length() == 4 && str.endsWith("ly"))
return true;
return false;
}
Avoid multiple false return statement as return value is true only for condition if(str.substring(str.length()-2).equals("ly")). Following code is for reference.
public boolean endsLy(String str) {
if(str.length()>=2){
if(str.substring(str.length()-2).equals("ly"))
return true;
}
return false;
}
Every now and then there is a need to store a boolean value only once (to record that it has changed from false to true or vice versa) in a loop, while executing the loop to the end but not caring anymore about changes in the boolean value. Example:
public static boolean dbDelete(Collection argObjectCollectionToDelete) {
boolean result = true;
for (Object object : argObjectCollectionToDelete) {
boolean dbDelete = dbDelete(object);
if (!dbDelete) {
result = false;
}
}
return result;
}
Is there some way to execute the equivalent of the code
if (!dbDelete) {
result = false;
}
or
if (!dbDelete && !result) {
result = false;
}
in a more elegant way, preferrably in one line?
How about:
result &= dbDelete(object);
This is equivalent to:
result = result & dbDelete(object);
So it will only be true if result was previously true and dbDelete returned true.
if (!dbDelete(object)) {
result = false;
}
result = dbDelete(object) ? result : false;
Try putting more meaning into your variable names - it makes things easier.
public static boolean dbDelete(Collection argObjectCollectionToDelete) {
boolean completedSuccessfully = true;
for (Object object : argObjectCollectionToDelete) {
boolean dbDelete = dbDelete(object);
if (completedSuccessfully && !dbDelete) { //won't change anymore after failure
completedSuccessfully = false;
}
}
return completedSuccessfully;
}