After else statement finish test case - java

Could somenone, please provide me with answer.
Namely, My for loop looks like (it actually founds element which has no atribute disabled, but what if all elements are disabled, then I want to finish test and sent message). So how can I rewrite this loop to be if/else.
if (disabled == null) {
dropdown3.selectByValue(option.getAttribute("value"));
break;
}
Message which I want to show as end of test should be:
ELement is not enabled, so finishing test
and go directly to
driver.close();
And finish test.

First, you can check for undisabled values
if (undisabled =! null) {
dropdown3.selectByValue(option.getAttribute("value"));
}
else {
System.out.print("All features are disabled.");
break;
}

Related

Why when I have "valid = true;" under How many you want to order, in debug mode it the code works but running it does not?

But if I put it to "valid = false;" it does not work in debug or running.
In fact even running the code, I can't type anything after the "Do you want to order anything else?", no matter if it's in debug or running mode.
Am I missing something? After asking "how many you want to order" and you put in a number after it should ask "do you want to order anything else" which is does but then I can't type and break out of the do while loop. Everything else is working up to that point.
do {
boolean itemValid = true;
while (itemValid) {
System.out.println("Please enter an item name: ");
String enterItem = scnr.nextLine();
if (keepTrack.containsKey(enterItem)) {
System.out.println(keepTrack.get(enterItem));
itemValid = false;
} else {
System.out.println("Sorry we don't exist.");
continue;
}
System.out.println("How many do you want to order?");
int enterQuan = scnr.nextInt();
yourOrder = enterQuan;
valid = false;
}
System.out.println("Do you want to order anything else?");
String yesNo = scnr.nextLine();
if (yesNo.equalsIgnoreCase("n")) {
valid = false;
} else
break;
} while (valid);
Two problems with your code. First, probably unnoticed yet:
do ...
if (keepTrack.containsKey(enterItem)) {
System.out.println(keepTrack.get(enterItem));
itemValid = false;
} else {
System.out.println("Sorry we don't exist.");
continue;
}
When your input is "invalid", you turn into the else branch. The else branch continues the loop. The loop depends on value. Thus: as soon as you start with value=true, and then have an invalid input, you end up with a never-ending loop. Because nothing between the loop start and the continue statement will ever change the conditions that would end the loop.
Your actual question: when you call int enterQuan = scnr.nextInt() that does not consume the "ENTER" that you typed on the console. See here for details.
And there is another problem:
if (yesNo.equalsIgnoreCase("n")) {
valid = false;
} else
break;
}
When the user enters n or N, you go valid=false which ends the outer do-while loop. Thus: when the user enters anything else, the elsepath is taken. What is to be found in the else path? A break. Which also ends the do-while loop.
In other words: your code does exactly what you told it to do: to end the do-while loop, one way or the other.
The real answer is: you need to be much more careful what you put in your code. Each and any character matters. And when you put something into your code for an experiment: remember that it is there, and has effects.

how to identify data is displaying or not in selenium

condition:how To check data is displayed or not
Boolean isPresent3 = driver.findElements(By.cssSelector(".input-horizon.horizon-program-guide.form-control.ng-pristine.ng-untouched.ng-valid.ng-not-empty.ng-valid-min")).size()> 0;
if (isPresent3 == true) {
System.out.println("Aflam data exists");
}
else {
System.out.println("Aflam data does not exists");
}
Boolean isPresent3 = driver.findElements(By.cssSelector("csspath")).size()> 0;
this code some time works sometimes not any good solution that works evrytime
To check whether the element is visible use isDisplayed() method which returns boolean values (ie)
List<WebElement> element=driver.findElements(By.cssSelector(".input-horizon.horizon-program-guide.form-control.ng-pristine.ng-untouched.ng-valid.ng-not-empty.ng-valid-min"));
System.out.Println(element.size());
if(element.isDisplayed()==true){
System.out.Println("element is present");
}
else
{
System.out.Println("element is not present");
}
It checks whether the element is present on the page. To check visibility of the element you should use "isDisplayed()". My suggestion is to use both the conditions.
List<WebElement> elem= driver.findElements(By.cssSelector(".input-horizon.horizon-program-guide.form-control.ng-pristine.ng-untouched.ng-valid.ng-not-empty.ng-valid-min"));
if(elem.size()> 0){
if(elem.get(0).isDisplayed()){
System.out.println("Element is dislayed and present");
}
}
else{
System.out.println("Element is not present");
}
Well, if it works sometime and not all the time then it may be the case where the element takes time to be available in dom and your findElements statement executed before it's available!
Quick and dirty work-around is, add sleep, for example Thread.sleep(3000).
Anther work-around is you can have waitForElementpresent condition in try catch block and in catch block you can set flag false!
If you are using qaf you can use assertion/verification available with driver and element object where you don't need to use any of above work-arounds. For example in your case it may look like:
$("css=csspath").verifyPresent(); // checks only presence in dom.
$("css=csspath").verifyVisible();// ensures present and displayed

Multiple error notifications

I have a registration page where the user has to enter personal information about themselves, if something entered is invalid then error notifications should pop up
if (!PhoneNumber.startsWith("055") || !PhoneNumber.startsWith("050") || !PhoneNumber.startsWith("056") || !PhoneNumber.startsWith("052")) {
// does not match
contact_number.setError("Please enter a valid phone number");
return;
}
if (TextUtils.isEmpty(password) )
{
VendorRegPassword.setError("Please enter your password");
return;
}
else if (password.length() < 6)
{
VendorRegPassword.setError("Please use more than 6 characters");
return;
}
if (TextUtils.isEmpty(email) || !email.contains("#") )
{
VendorRegEmail.setError("Please enter a valid email address");
}
Independently they work on their own but when put together it does not work properly, also the phone number error does not work properly, can somebody help me with this?
The other answer is correct; the return statement simply prevents all checks to be executed. And in this case, you want all validations to take place, as each validation has a different way of informing the user about the problem.
Beyond that: from a "clean code" perspective you should be careful to simply stuff all validations into the same poor method. Instead: structure your code so that it clearly expresses what is going on, like:
private void validateAll(PhoneNumber number, Email email, Password password) {
validatePhoneNumber(number);
validateEmail(email);
...
and separate helpers like
private void validatePhoneNumber(number) {
boolean validPrefix = false;
for (String validPrefix : PREFEIXES) {
if (phoneNumber.startsWith(validPrefix) {
validPrefix = true;
}
}
if (!validPrefix) {
contact_number.setError("Please enter a valid phone number");
}
}
for example. And please note - I fixed another bad practice (your idea to simply hard-code all valid prefixes). You always want to put such information into some constant set/list; so that you have exactly one place in your code that knows what those prefixes are.
They are not working together properly because you are returning from the method in if or else ifconditions. Remove return statements from if and else. Because return will terminate the execution of method, so further code will never be executed due to return.
They are working separately because, there is no need to execute further conditions (no further conditions at all), so returning from method seems correct solution.

Unreachable code in swtch statement

I have written following method in Java. But I get error message unreachable code on the line containing return (Constants.SUCCESS);
If I comment that line, I do not get error message. Now my doubt is why I do not get error message if I comment that line? There is no return value of SUCCESS to the calling portion if I comment the line. I thought there should be one return statement and there are none if all "if loops" and default is not getting executed. I thought last return statement will execute in any case. I tried return (Constants.SUCCESS) statement at the end also (Commented line), but no luck.
So for returning success, do I need to return success after each "if" loop under every case statements (creating "else" part for each).
static int validateStartAndEndStringOrder(String startStr, String endStr, ArrayList<String> swaraPool, Constants.PatternType ptrnType) {
switch (ptrnType) {
case AROHA_INCREASING: {
if (swaraPool.indexOf(endStr) < swaraPool.indexOf(startStr)) {
System.out.println("End string is before the start String");
return (-1);
}
}
case AROHA_DECREASING: {
if (swaraPool.indexOf(startStr) < swaraPool.indexOf(endStr)) {
System.out.println("End string is before the start String");
return (-1);
}
}
case AVAROHA_INCREASING: {
if (swaraPool.indexOf(endStr) < swaraPool.indexOf(startStr)) {
System.out.println("End string is before the start String");
return (-1);
}
}
case AVAROHA_DECREASING: {
if (swaraPool.indexOf(startStr) < swaraPool.indexOf(endStr)) {
System.out.println("End string is before the start String");
return (-1);
}
}
default: {
System.out.println("Invalid Enumeration Type");
return(-1);
}
return (Constants.SUCCESS);
}
//return (Constants.SUCCESS);
}
switch ... case 1 ... case n ... default covers all control paths (the default will catch all remaining cases). Since you return explicitly out of each one, there's no way program control can go beyond that switch block.
Your compiler is being helpful in emitting the error.
Use break; statements between each case in the switch block to move control flow to the end of the block.
I suspect you want to add a break; at the end of your case blocks. Otherwise the code just runs from top to bottom (like anywhere else in your code)
If you place a break; it will jump outside the switch block which appears to be what you want.
e.g.
case AROHA_INCREASING: {
if (swaraPool.indexOf(endStr) < swaraPool.indexOf(startStr)) {
System.out.println("End string is before the start String");
return (-1);
}
break; // without this, the thread will run the next case: block.
}
You default section contains
{
System.out.println("Invalid Enumeration Type");
return(-1);
}
return (Constants.SUCCESS);
What do you expect?

Predicate Method yes/no/maybe response

I'm trying to write a program where the run method calls a predicate method that asks someone "Do you want to go to a movie tonight?". If the user enters "yes" to the question I want the program to say "Ok. Let's go tonight." If the user enters "no" I want the program to print "That's cool lets go next week." But if the user enters "maybe" I want my program to say "it's a yes or no question" then ask the question again "Do you want to go to go to a movie tonight? " and then wait for a user to enter a response again. The problem I' having is if the user enters "maybe" the program says "it's a yes or no question" then automatically prints "that's fine lets go next week." How do i fix this incorrect logic in my program? This is a question in the chapter focusing on parameter passing in my book. Did I correctly design my program to pass the string value from the run method to the isYesorNo method for what I'm trying to write?
import acm.program.*;
public class MoviesTonight extends ConsoleProgram {
public void run() {
String answer = readLine("do you want to go to a movie tonight?");
if (isYesorNo(answer)) {
println("Ok. Let's go tonight");
} else
println("that's cool let's go next week");
}
private boolean isYesorNo(String response) {
while (!response.equals("yes") && !response.equals("no")) {
println("it's a yes or no question");
break;
}
return (response.equals("yes"));
}
}
I would use a enum for returning the answer if you want something other than true/false, but still a discrete set of values.
For example:
enum Answer {
YES,
NO,
MAYBE
}
Then switch on the enum instead of if/else (down to personal preference, I think a switch statement is cleaner), putting all in a while loop:
boolean yesOrNo = false;
while (!yesOrNo) {
Answer answer = readAnswer("do you want to go to a movie tonight?");
switch (answer) {
case ANSWER.YES:
println("Ok. Let's go tonight");
yesOrNo = true;
break;
case ANSWER.NO:
println("that's cool let's go next week");
yesOrNo = true;
break;
default:
println("it's a yes or no question");
break;
}
}
So basically if the answer is MAYBE, yesOrNo doesn't get set to true so the while loop is executed again when the condition is checked.
The readAnswer method should be a private static helper method and return the correct enum value based on the input string. Either do this by using an if/else or switch statement on the string.
Two things here:
The logic is wrong. If the input is "maybe", then your isYesOrNo will print out "it's a yes or no question", but then returns false, which gives the additional (problematic) output ""that's cool let's go next week".
The break in the loop does not make sense, which is the real problem. The loop should continue unless the condition is meet, it should break out on the first execution of the loop.
In addition to the suggestions already provided, the isYesOrNo method contains a significant error, which is in fact the answer to your base question:
The problem I'm having is if the user enters "maybe" the program says "it's a yes or no question" then automatically prints "that's fine lets go next week." How do i fix this incorrect logic in my program?
return (response.equals("yes"));
If the response is 'maybe', then it does not equal 'yes', and the return will be false -- this is why it immediately prints, "that's cool let's go next week". That is in fact the 'else' condition you supplied for if(isYesOrNo(answer)).
As it stands, you're checking to see if the response is yes/no, starting a while loop which runs if it isn't yes/no, breaking the while loop prematurely, and then returning false on one of the conditions which spawned the while loop in the first place (read: not 'yes'), which finally gets handled as a 'no' (which may not be the case).
Try something like the following, if you want to use if-else:
public void askQuestion(){
String response = readline("Do you want to go to a movie tonight?");
getYesNoResponse(response);
}
public void getYesNoResponse(String answer){
if (answer.equals("yes"){
//print the yes response
} else if (answer.equals("no") {
//print the no response
} else {
askQuestion();
}
}

Categories

Resources