How to break the loop if webelement value matches to excel value - java

I am using application which has 19 pages. on each page there are 10 accounts and 10 checkboxes in front of them.
I have kept a list of some accounts in excel sheet and want to read account number in excel one by one, match it with accounts on webpage, if value matched->set the checkbox in front of that account and move for the next account in excel.....and this way repeat till last account is matched in excel list.
If account is not matched with any of the 10 accounts on webpage, i need to click on next arrow(present below account list on webpage) and check if account number matches with any of the account on new webpage.
code is as below
String data=null; //to get value of account on webpage
int count=0;
do{
for(count=0;count<=9;count++)
{
data= (String) al1.get(count); //al1=List of accounts on webelement
if(stg.equals(data)) //stg=account read from execl
{
utl.checkbox_clicking(data);//calling method to set checkbox if value matches
break;
}
}
utl.Weblement_Click("*name of weblement of next page arrow*");
al1 = utl.Account_List(); //loading new account list on next page in List
}while(stg.equals(data));
There is some problem in logic. Can somebody suggest the what changes i should make?

I see that your problem is when you find what you need you just execute break. But break go just out the inner loop, and not the outer.
So without trying to change anything in your code and reorganize something I want to tell that there is something unused in java, maybe because of unreadability of the code, that called labeled block. Maybe one of the only uses of it is to break out of outer loops. I hope it will help you and it's the right solution for your problem.
Note that most of the time if you find yourself using it maybe you need to change your loop. In your case I would go with something like while loop with two conditions: one for 10 account in each page and one when you can't find more pages.
here's a short tutorial about that:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
So in your code I just added the the first statement and the break line.
pagesLoop:
do {
for (count = 0; count <= 9; count++) {
data = (String) al1.get(count); //al1=List of accounts on webelement
if (stg.equals(data)) //stg=account read from execl
{
utl.checkbox_clicking(data);//calling method to set checkbox if value matches
break pagesLoop;
}
}
utl.Weblement_Click("*name of weblement of next page arrow*");
al1 = utl.Account_List(); //loading new account list on next page in List
} while (stg.equals(data));

Removing unnecessary loop and also missed count should be count<9 instead of count<=9
for(int count=0;count<9;count++) {
String data = (String) al1.get(count); //al1=List of accounts on webelement
if(stg.equals(data)) //stg=account read from execl
{
utl.checkbox_clicking(data);//calling method to set checkbox if value matches
break;
}
}
utl.Weblement_Click("*name of weblement of next page arrow*");
al1 = utl.Account_List(); //loading new account list on next page in List

Related

Why can't selenium webdriver see the elements on the webpage? (NoSuchElementException)

I have my selenium code here
System.out.println("Selects selected");
Methods methods = new Methods();
/**
there's some code here, but it's just a lot of driver().findElement() and updating values in fields. It works OK
**/
driver().findElement(By.xpath("//*[#id=\"updateclient\"]")).click();
Thread.sleep(5000);
driver().findElement(By.xpath("//*[#id=\"quoteclient\"]")).click();
Thread.sleep(15000);
/* Selects the Zurich Quote (Only one currently working) */
driver().findElement(By.xpath("//*[contains(#id, 'quote-0')]//*[contains(#alt, 'Zurich')]")).click();
/* Select the Apply for Big 3 CIC button */
driver().findElement(By.xpath("//*[#id=\"apply_for_big3\"]")).click();
//Just wait for the page to load properly
Thread.sleep(2500);
/**
* Now we are at the big3 eligibility page. We will need to enter the client details.
* Because we want to check all the outcomes that iptiQ have given us, we're going to do
* this in a loop.
*
* This loop will set the client details, answer the questions, and then go through to the
* quoting page.
*
* When the client has been quoted for the values set, we will check that the premium matches
* the expected value.
*
* At the end of each iteration, the user will be returned to the Big3 eligibility screen so that
* the next set of values can be set.
*/
//Get the fields. -------
//This is the bit that keeps failing and it should not be failing
// because the elements are all present on the page
WebElement EligibilityTitleOne = driver().findElement(By.xpath("//*[#id=\"title_1\"]"));
WebElement EligibilityForenameOne = driver().findElement(By.xpath("//*[#id=\"forename_1\"]"));
WebElement EligibilitySurnameOne = driver().findElement(By.xpath("//*[#id=\"surname_1\"]"));
String[][] SumAssuredCases = QuoteGraph.SingleLifeSumAssured;
for(int i=0; i<SumAssuredCases.length; i++){
/**
//Extract all the required values from the array
int AgeNextBirthDay = Integer.parseInt(SumAssuredCases[i][1]);
String SmokerStatus = SumAssuredCases[i][2];
String SumAssured = SumAssuredCases[i][5].replace(",","");
String PolicyTerm = SumAssuredCases[i][6];
String ExpectedPremium = SumAssuredCases[i][7];
String ExpectedCommission = SumAssuredCases[i][8];
**/
int AgeNextBirthDay = 25;
String SmokerStatus = "NonSmoker";
String SumAssured = "10000";
//We are going to use a pre set name, as names do not affect the premium.
EligibilityTitleOne.clear();
EligibilityTitleOne.sendKeys("Mr");
System.out.println("Set customer 1 title");
EligibilityForenameOne.clear();
EligibilityForenameOne.sendKeys("Tester");
System.out.println("Set customer 1 forename");
EligibilitySurnameOne.clear();
EligibilitySurnameOne.sendKeys("Testeez");
System.out.println("Set customer 1 surname");
//Now we are going to set the sex to be male. This does not affect the premium.
Select clientOneSexSelect = new Select(driver().findElement(By.xpath("//*[#id=\"gender_1\"]")));
clientOneSexSelect.selectByVisibleText("Male");
System.out.println("Set customer 1 to male");
//Now we need to set the smoker status from the value in the customer profile
Select clientOneSmokerStat = new Select(driver().findElement(By.xpath("//*[#id=\"smoker_1\"]")));
if(SmokerStatus.matches("Smoker")) {
clientOneSmokerStat.selectByVisibleText("Yes");
System.out.println("Customer 1 is a smoker.");
} else {
clientOneSmokerStat.selectByVisibleText("No");
System.out.println("Customer 1 is not a smoker.");
}
//Now we need to calculate the date of birth
String customerOneDob = methods.DOBFromAge(AgeNextBirthDay);
driver().findElement(By.xpath("//*[#id=\"dob_1\"]")).sendKeys(customerOneDob);
System.out.println("Customer 1 date of birth set to " + customerOneDob);
//Now we need to set the sum assured value
driver().findElement(By.xpath("//*[#id=\"sum_assured\"]")).clear();
driver().findElement(By.xpath("//*[#id=\"sum_assured\"]")).sendKeys(SumAssured);
System.out.println("Sum assured set to £" + SumAssured);
//Select the update client details
driver().findElement(By.xpath("//*[#id=\"update_lead\"]")).click();
//Wait for update to complete
Thread.sleep(1000);
System.out.println("The changes have been saved.");
Thread.sleep(2500);
}
and all the driver().findElement(By.xpath()) have worked fine up until the point when I need to fill out the form repeatedly in the loop, and suddenly I start getting the NoSuchElementException error.
I don't understand why I am getting the error, when the webpage I am on has all the fields, I have taken the xpaths directly from [right click]->[copy xpath] in devtools.
The fields are definitely there and the XPATH I am using is correct, I've checked multiple times and so have my colleages, but I don't know why it gets to just before the loop and then stops working.
I've also tried findElement(By.id()) but that still gave me the same error. Selenium is acting as though the elements don't exist, even though they do.
Check if the elements are with in IFrame then use driver.switchto.frame (frmaelocator);
If it's on a different tab use windowhandles

JAVA Input Comparison & Ignoring Negative Outcome

I'm new to JAVA and am struggling with a specific issue that I couldn't find an answer to so I decided to ask the good people of StackOverflow.
I am trying to build an ATM program. I have created an array of objects (The clients of the bank) with properties such as cardnumber, pin, balance, etc. And when any user will try and "log in" to the ATM he should type in his card number.
In the code below I tried to simulate the ATM going through the array of Clients and checking the input number with all the existing card numbers of each customer until it finds a match, and it works fine. The problem is that if it finds a match with client at position 10 it will display "Inexistent Card" 10 times before succeeding.
So I wanted to ask if there is a way for the program to ignore all these mismatches and only continue if it finds a match. And give me the "Inexistent Card" only when it finds 0 matches.
for (i = 0; i < clients.length; i++) {
if (input.equals(clients[i].accountnumber)) {
System.out.println("Welcome");
} else {
System.out.println("Inexistent Card");
}
}
consider using a found boolean variable
boolean found = false;
for (i = 0; i < clients.length; i++) {
if (input.equals(clients[i].accountnumber)) {
System.out.println("Welcome");
found = true;
break;
}
}
and then after the loop
if (!found) {
System.out.println("Inexistent Card");
}
That is exactly what you've written!
Think about it a bit more: You don't know the account doesn't exist until you've searched all the accounts and not found the one you want. You need to organise your code the same way. Just because clients[0] is not the one you are looking for, clients[1] might be, so you can't say "non existent" just yet...
The most simple way to achieve this:
int indexOfMatchingCard = -1;
for (... {
if (match) {
indexOfMatchingCard = current index
Afterwards, you can check if indexOfMatchingCard is >= 0; at the same time it tells you which of your cards matched. Just make sure to not reset that marker if you later find that other cards are not matching!
If you don't need to remember the matching index; you can use a simple boolean marker (which you initialize to false once; and change to true when on match).

for loop jumps to last number in java android development

Hi I am making an android App, I want to add some values to a database and I want to do N times so I used a for loop as seen below:
private void addCodeToDataBase() {
for (int i = 1; i <= 100; i++) {
//indexnumber is a TextView
indexNumber.setText("Please enter the TAN code for Index number " + i);
//tanCode is an EditText
if (tanCode.getText().toString() != null) {
//index here is just an int so i can use the i inside the onClick
index = i;
//add is a button
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String codeText = tanCode.getText().toString();
dbHandler.addcode(index, codeText);
}
});
} else {
Toast.makeText(addcode.this, "Please enter your code !!!", Toast.LENGTH_LONG).show();
}
}
}
but what I am facing here is the for loop jumps to 100 at the first run, What I mean is the text will show :
Please enter the TAN code for Index number 100
it skips 99 numbers!! how would I fix it ?
It's Because your for loop executes so fast that you can't notice that the change of the text.First i is 0,and then it becomes 1,then the text will be "Please enter the TAN code for Index number 1" ......
your loop is working correctly but it is replacing text on each iteration that's why you think that it is jumping on last value please use break point and debug you will see each value on each iteration or use log in which you will see each value
It's not easy to imagine what your code does without seeing your declarations of indexNumber, tanCode, index, and, in particular, add. So, e.g., we don't know how often your if condition yields true.
However, most probably, the problem is that your assignment add.setOnClickListener(...) is just iterated with no user interaction in between. Now if you repeatedly assign something to your add (whatever that is), the last assignment will win.
If you want 100 buttons, you'll need to have an array or List of buttons to press, where each has a different tan code. If you want one button that repeatedly asks for the different tans, then you have to assign the data for click i + 1 only after click i has been handled, i.e. in the on click listener.
To give more specific help, we would need to know how your user interface should look (how many widgets of what kind) and how each widget should behave.

How to update only the last elements's first index in a List?

Consider the following code:
public void updateUser(Login login) {
UserExposableDO userExposableDO= new UserExposableDO(login);
for (int i = 0; i < (userList.size()-1); i++){
userList.set(i,userExposableDO);
}
}
This code updates each and every user in the list.
The userList gets filled whenever a user logs in. How do I update the status for each user after he logs out.
In simple words, I need to set the status of the latest or last user. The index of the status is 3.
I need to set the status of the latest or last user.
Just looking at your question. Just get the last element of the list. And update it's first index.
list.get(list.size()-1)// now you will get the last user
then
userList.set(0,userExposableDO)

Insertion of strings into an ArrayList using a binary search in Java?

So here is my problem: I am trying to do a form of insertion sort. Actually, I am trying to search through an ArrayList using a Binary Search algorithm and find where to insert a string. What I have so far sort of works. It is in partial order. I have been stumped on this for over a week! Below is my code:
EDIT: Sorry I think I confused people. My question is how can I edit this to work properly. It inserts my objects in partial order. I need it to be complete order! I do not know where this is happening. I have far too much data being parsed to debug this line for line too.
private void insertOrdered(int frontParameter, int endParameter, TwitterData user) {
int front = frontParameter;
int end = endParameter;
int mid = (front+end)/2;
if (front > end) {
if (user.getUsername().equalsIgnoreCase(users.get(mid).getUsername()))
users.get(mid).addTweet(user.getTweets().get(0));
else
users.add(mid, user);
}
if (user.getUsername().toLowerCase().compareTo(users.get(mid).getUsername().toLowerCase()) < 0) {
insertOrdered(front, mid - 1, user);
}
else if (user.getUsername().toLowerCase().compareTo(users.get(mid).getUsername().toLowerCase()) > 0) {
insertOrdered(mid + 1, end, user);
}
else { //will get to this case if the usernames being tested are equal
users.get(mid).addTweet(user.getTweets().get(0)); //if the user is already in the list, just add the tweet. It is assumed that the user being passed in will only have one tweet tied to their information hence the get(0)
}
}
Just for some background information, I am using this for an ArrayList of Twitter usernames and their associated tweets. The parameter passed, user, is a TwitterData object of a class I wrote. For all intensive purposes all you need to know if I can retrieve the username and a list of tweets that user may have tweeted. Below is a test output of the first 100 users of the list to show you what I mean by it partially working.
First 100 users output:
4colorrebellion
50BandBuckie
2996mymy
20120040
_littlethugg
_IndyaWithaWHY_
__PrettyMistake
__Mannyy24
_MikeFishh
_NikeDeshaun_
_TinaBeana
_PrincesaNessa
_LoveInPaaaris
_Victoria_Ortiz
adriannstacey21
ahansen718
action_packed_
Alicemegan93
alexgracehunter
AlishaaShaffer
arowsey_15
Amy_Vee
allycolucci
AmbiTious___xO
aguss__A
averybrownn
babbyyy_itsREAL
ando775
bburns1117
amberdorais
AshMarieMonica
Ashton_45
_SarahJustine
BlasianCocaine
belieber_pride
AyeeIts_DeeDee
BrianHodges
BritFranceNews
Big_Red911
BiteMy_SlimJim
BadGirlYon
Cemonee_Allisse
cathy_riveros
byby_35
CEOSIXX
busybeekatie
ChelsiKatherine
BOOBtifulJohnny
Coolie_Mackin
coralreefer420
CrashBandaCooch
codyalexander23
cubanrice
corrinea143
Cyndi_R82
danny728_
dbangin
ASNievera
DeAndre_Johnson
Deion_Hungry
DStudmuffin
cowellEmma
expired_data
Dr_drew_V93
feather_hinn
DominiqueQ2
getbackamistake
Da_Dirty_Dern
dudeimisaac
elennatalbert
evillurking
fANNcy_
covolm4
HimOverHere
DameLush
erinnnroach
freaky_fahfah
freesugardaddy
elhotpocket
FollowMandy
HaileyySorenson
DomoNinjaSwagg
IamSalinaScott
fredthemarauder
IAmTHATguy_1
facucuellar
iDream_Mindless
hirschy_kiss94
freshmoney5
HannahMcC_x
GarrieBrocato
AyeeeCali
iSexTattedDudes
Illumi_Lani
itsyunk
jahzzi
Jamie_Hill101
iHeartAudiooooX
jaymethornley
JasonMyers18
One more thing, the last else case does work properly. I have eliminated any kind of dual users being submitted to the ArrayList.
Any ideas?
This would be a lot simpler if you just inserted elements anywhere in the list and called Collections.sort() it would take the same amount of work as you already calculated for your insertion O(n*logn)

Categories

Resources