Loop to search page for unknown element - java

I am new to Java test automation and trying to write a simple for statement that will find the existence of a particular account number that identifies the element that is present.
My problem is that I can't get the loop to go through more than once. It seems that it breaks out of the loop right away when the condition is false.
I have exhausted the search. Any pointers or example. Appreciate it folks.
Here is the complete cssSelector format for my element I am trying to loop through:
#edit_account_**1201** > div.row.delete-mode.hideout > div.col-md-4 >
div.btn.btn-danger.btn-sm
Simply, what I would like to achieve since I know the range of the edit_account numbers and the format is to loop through the range, lets say 1200 -1250. And Once the element/cssSelector if visible and present I break our of the loop. :-)
for(int i =1200; i<1250; i++){
System.out.println("Checking through now");
if(driver.findElement(By.cssSelector("#edit_account_"+i+DELETE_CONFIRMATION_BUTTON)).isDisplayed()){
driver.findElement(By.cssSelector("#edit_account_"+i+DELETE_CONFIRMATION_BUTTON)).click();
System.out.println("Account number deleted is:" + i);
break;
}
}

I bet you are getting an exception when you try to locate the initial element. Do you see an exception? If so, can you provide the stack trace?
Consider grabbing all the elements you need first with:
List<WebDriver> elements = driver.FindElements(By....whatever your locator is...)
And, then iterating through the list with a loop and running your assertions or conditional logic.

You can have two solution :
Try using driver.FindElements which will not throw an exception or
Try to catch the exception and continue back to the beginning of the loop after that.
loop{
try{
if(){
driver.findelement....
}
}
catch(){
}
}

Related

Unexpected infinite loop after input reading

I'm trying to create a program that keeps asking a question until the user presses enter. But for some reason, the program goes into an infinite loop that continuously outputs:
"Enter the operation: You need to add '[' at the beginning of the set."
If you accidentally do not follow the rules. Now, the program should print that message but only once. I think the loop continuously asks for the operation but it goes straight to the error (If you do not enter anything, I guess that counts as not using an [ at the beginning).
I already know how to solve it but because I tried everything!! I am not sure how my solution changes anything... Can you give me advice on how to solve it and/or explain to me what is it about the do-while loop implemented at the end that does the trick?
Edit: TextIO is a class written by Eck, D. J. in his book. I will link the chapter where it gives the code here: http://math.hws.edu/javanotes/c2/s6.html
The problematic code is
while (true) {
System.out.print("\nEnter the operation: ");
TextIO.skipBlanks();
if (TextIO.peek() == '\n') { //There is no operation, end the program.
break;
}
try {
calculation();
}
catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
The solution I implemented looks like this:
while (true) {
System.out.print("\nEnter the operation: ");
TextIO.skipBlanks();
if (TextIO.peek() == '\n') { //There is no operation, end the program.
break;
}
try {
calculation();
}
catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
do {
ch = TextIO.getAnyChar(); // Read ahead the "enter".
} while (ch != '\n'); //If necessary, make sure to stop the error message and keep the loop going.
}
Thanks, guys!!
It sounds like you're using TextIO class from David J. Eck's Introduction to Programming Using Java, Eighth Edition book.
According to the source of the class:
[TextIO.peek()] returns the next character in the current input source, without actually removing that character from the input.
You're checking the input actually without removing it. That's why in the next iteration, the loop keeps reading the same bad input, and throwing the exception indefinitely.
Also your fix performs what is lacking after calling peek(). Removing the char from the input.
Hence, replacing peek() by getAnyChar() in your first attempt solves the problem.
I'm not sure what's TextIO, you should use the standard Scanner class.

I Can`t understand what the condition mean

What does this condition mean in Java?
while(n>0)
I'm a newbie at Java and I've never seen this kind of code in conditions.
just do a search on while loop.
here is a link to wiki
while(n>10)
{
// do stuff..
}
.. simply means execute that block of code as long as n > 10.. normally you would have something inside that code block to make n greater than 10 at some point.. otherwise you would have an infinite loop.. which is bad..
It means that as long as the variable named "n" evaluates to a value greater than 0, what ever logic is inside the while loop code block will continue to execute. FYI - a quick Google search will reveal thorough information and examples on while loops.
the expression inside of a while loop is always a boolean expression;
here you are expressing that a variable, n, is greater than 0.
if true, you enter the loop,
else, you do not.
For a situation like this, it is likely that n is an integer
https://www.tutorialspoint.com/java/java_while_loop.htm

How to reduce element searching default time in appium

I have just noticed that Appium & Selenium is taking at least 2 minutes to find element when element is not there.
I want to reduce that time for search.
Code is :
if(!driver.findElements(By.id(AppConstants.notificationcount)).isEmpty())
{
// DO SOMETHING
}
else
{
System.out.println("No Element available");
}
Now most of time my element not available so I want appium to check it and redirect quickly to ELSE part , but it is taking long time , Any solution?
Have you checked your implicit wait time?
It is 0 by default, but maybe you are setting it somewhere to a value > 2 mins:
driver.manage().timeouts().implicitlyWait(timeInSeconds, TimeUnit.SECONDS);
If your implicit wait time is bigger than 0 and you are searching for an element with
driver.findElements(...);
but your Element does NOT exist, then Selenium will wait the WHOLE specified time!
Selenium only does not wait, when at least one element is found. In this case it will search the page once and return immediately with the list of elements found.
So findElements() is without restriction great to check the existence of an element, but only good for checking non-existence when you specified a very low implicit wait time (or the default 0).
If you absolutely need an implicit wait time > 0 for whatever reason, then you can create your own method that handles this like in this solution.
In your case you could set implicit wait time to 0 right before your posted code:
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
// then follows your code:
if(!driver.findElements(By.id(AppConstants.notificationcount)).isEmpty())
{
// DO SOMETHING
}
else
{
System.out.println("No Element available");
}
If you need an implicit wait time other than 0 elsewhere then just set it back to the original value after your piece of code.
The quicker way to check is store the elements in a list and then check if it is empty
List<WebElement> elements = driver.findElements(By.id("AppConstants.notificationcount"));
if (elements.isEmpty()) {
System.out.println("No Element available");
}else{
elements.get(0).click();//if present click the element
}
Hope this helps you.

Meaning of "for (;;)"? [duplicate]

This question already has answers here:
How does a for loop work, specifically for(;;)?
(6 answers)
Closed 9 years ago.
What is the meaning of for (;;)?
I found it in a certain base class and I cannot find explanation for in on the net.
Please also explain when and how to use this expression
It's an infinite loop. It has no initial condition, no increment and no end condition.
It's the same as
while(true) {
//do stuff
}
You can use it when you need something to be repeated continuously, until the application ends. But i would use the while version instead
It is read "for ever". the default for the condition is to evaluate to true.
When should you use it? If you don't want the loop to end (as is common in servers) or when the end condition is naturally known only in the middle of the loop, in which case you can use break:
for (;;) {
String in = get_input();
if (in.equals("end"))
break;
System.out.println("you entered " + in);
}
This is not the best example, though. You can do without the infinite loop here. For example:
for (String in = get_input(); !in.equals("end"); in = get_input()) {
System.out.println("you entered " + in);
}
It means an infinite loop. It is not considered a good practice to use this. Instead try while(true)
In some cases where you want to do a task again and again, sometimes forever. Such cases you use an infinite loop. This can be done in many ways. Notable ones are,
Using while,
while(true)
{
// Task you want to repeat
}
Using for,
for(;;)
{
// Task you want to repeat
}
Note : You might have to be very much careful while implementing infinite loops as there exists a possibility of same problem recurring. It is a good practice to catch the exception and retry for some time and if still problem persist, break from the loop.

Source of Infinite Loop

Everytime I run this code, the console goes into an infinite loop printing "Please input a number". I do not understand why this is happening. Thanks in advance.
boolean check = true;
int temp = 0;
while(check==true){
try{
temp= asker.nextInt();
check = false;
}
catch(InputMismatchException e){
System.out.println("Please input a number.");
}
}
Edit: asker is a Scanner. The purpose of the code is to loop until an integer is inputted by the user.
The method asker.NextInt() is throwing an InputMismatchException, indicating that the input received from asker (assuming it's a Scanner) isn't actually an integer. This exception causes the loop to restart without setting check to false.
Print the exception within the catch block to get more information about the failure. But most likely, you're feeding your application something (lots and lots of something, if it's looping like that) that doesn't actually contain integer values.
You never want to actually "Use" try/catch--by that I mean don't use it as part of your program logic--this is what you are doing.
One big problem is that, like your app, you don't see the stack trace. Eating a stack trace in an exception is almost always wrong.
If you do have to catch an exception, handle it near the catch as well as you can, but it's better to set up your code so that the exception can't be thrown anyway.
Discard this advice if your teacher told you to do it this way, but remember in the back of your mind that it's poor form.
Also don't tell your teacher that it's poor form :) he either doesn't know in which case he won't understand why or he does know and is using this to show you how try/catch works.
What is asker, a Scanner? If nextInt() fails, it doesn't consume any input, so when you catch your exception and loop back around to try again, it ends up just reading the same bad input again.
You should do something in the catch block to consume the invalid input, so that the next time around, it can read some different input. Call asker.nextLine() maybe, and ignore the return value.
You need to break the loop and report why the loop occurs
boolean NotValid = true;
int temp = 0;
while(NotValid){
try{
temp= asker.nextInt();
NotValid = false;
break; // stop
}
catch(InputMismatchException e){
System.out.println("Please input a number. reason why:");
System.out.println(e);
NotValid = true;
}
}

Categories

Resources