This is my first post for help. Please correct me if you see anything wrong with my post.
I am trying to validate the sorting functionality in a web page with Selenium script (using java). here are the details...
First I go to a User search results page with multiple pages.
It has users with the details: user name, number of miles.
There is a sort filter drop down with values: Values A-Z, Values Z-A, Miles Most, Miles Least, Newest Members, Oldest members . by default the sorting is newest members.
Initially I just want to validate: Values A-Z, Values Z-A, Miles Most and Miles Least Since I could see those values in the search page.
For someone who is looking to solve the same problem. Below code worked for me in validating the sorting of all the string values in a page
//Declare Variables
int eleCount;
List<String> customerNameA = new ArrayList();
List<String> customerNameB = new ArrayList();
// Check for our Customer elements and count them.... replace xxx with your xpath
assertTrue(isElementPresent(By.xpath("xxx")));
elements = driver.findElements(By.xpath("xxx']"));
eleCount = elements.size();
System.out.println("Element count: " + eleCount);
for(int i = 2; i < eleCount; i++){
//Capture the customer name values
//replace xxx with your xpath & replace the value increments for each element in xpath with + i +
customerNameA.add(driver.findElement(By.xpath("xxx")).getText());
System.out.println(driver.findElement(By.xpath("xxx")).getText());
customerNameB.add(driver.findElement(By.xpath("xxx")).getText());
}
Collections.sort(customerNameA);
for (int i=0;i<customerNameA.size();i++) {
System.out.println("Customer Name from input: " + customerNameB.get(i) + "--Customer Name from sorted input: " + customerNameA.get(i));
if (!(customerNameA.get(i).equals(customerNameB.get(i)))) {
System.out.println("Customer Names not sorted: " + i);
break;
}
}
}
Related
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
I am trying to iterate over a table with an email criteria to retrieve all the records from the table row. I am getting this error hint
Type mismatch: cannot convert from element type User to Object[]
This is my attempt:
List<User> adminList = _adminDao.getSingleUser(searchName);
for (Object[] row: adminList) {
System.out.println(" ------------------- ");
System.out.println("first row: " + row[0]);
System.out.println("second row: " + row[1]);
}
Please how do I retrieve the above as array elements
The message tells you all you need to know:
This code:
for(Object[] row : adminList)
says: "I expect that each member of that List should be of type 'array of Object'".
Which sounds rather wrong. So, you have to step back and reconsider why you put down that code in the first place!
The list is already declared to contain objects of class User, so the straightforward way to use it would be.
for (User user : adminList)
If that is not what you need; then well, why did you declare adminList to be of type List<User>?
And just for the record: this really a very basic java problem. If you don't understand such basic things yet, you should spend some serious time on learning java first. There is absolutely no point in using frameworks like Hibernate (that come with a huge amount of complexity!) if you dont understand what a ClassCastException means and how to deal with it.
In other words: learn to crawl before trying to run!
You get a List<User>, so you have to work with the user object in your Loop:
List<User> adminList = _adminDao.getSingleUser(searchName);
for (User row: adminList) {
//Do anything with the user
}
BTW: _adminDao.getSingleUser should not return a list of Users.
Seems that you are trying to print all the member variables in an User object. So:
for (User row: adminList) {
System.out.println(" ------------------- ");
System.out.println("first row: " + row.getFirstVariable());
System.out.println("second row: " + row.getSecondVariable());
}
First you are iterating a list, not an object array.
The for need the correct list reference:
for (User row: adminList)
This is likely get a User called row (each iteration) in the adminList which is a collection of User object.
Second, if you want to get indexes, use a normal for. (or while, do while)
for (int i=0; i< adminList.size(); i++) {
System.out.println(" ------------------- ");
System.out.println("row: " + adminList.get(i));
}
or With foreach:
for (User row: adminList) {
System.out.println("row: " + row);
}
And if you want to print some predefined indexes, you don't even need to loop!
System.out.println(" ------------------- ");
System.out.println("first row: " + adminList.get(0));
System.out.println("second row: " + adminList.get(1));
Your loop should like :
List<User> adminList = _adminDao.getSingleUser(searchName);
int i = 0;
for (User row: adminList) {
System.out.println(" ------------------- ");
System.out.println(i" row: " + row);
i++;
}
Here it will execute code inside loop for each element in adminList.
Creating a basic post fix expression evaluator/calculator program in Java using Eclipse. I want to be able to store some statistics (listed below)
• The highest overall result value
• The lowest overall result value
• The aggregate value (all answers added together)
• The average answer (from all answers of all expressions)
• Total invalid expressions entered
• Total valid expressions entered
Current code: http://pastebin.com/EijjR6jq
Any guidance appreciated, thanks.
An easy solution would be to create an arraylist to store the values (before printing). This arraylist will contain all of the values which you have gotten so far. Sorting it will get you the highest/lowest overall value, summing it up & dividing that sum by the number of elements in the arraylist will get you the aggregate value & average answer.
As for the invalid and valid expressions, counters could be implemented to keep track of those. Increment the respective counter (valid/invalid) depending on the expression entered.
So for example, it will look something like below.
Scanner input = new Scanner(System.in);
int invalidNumberExpressions = 0; //counter for invalids
int validNumberExpressions = 0; //counter for valids
ArrayList<String> values = new ArrayList<String>(); //Arraylist for calculated values
while (true) {
... //Omitted
if ("+".equals(part3)) {
// Note that your calculation ends up with a string, and not a float
values.add(part1 + " " + part3 + " " + part2 + " " + " = " + (number1 + number2));
System.out.println(values.get(validNumberExpressions));
validNumberExpressions++;
}
// Omitted
Could also consider using switch statements & refactoring out the common section of code in both parts into another method so you don't have to repeat the whole section twice. Looks cleaner, too.
Something like the below for the switch statement. I'll leave the refactoring part to you.
switch (part3) {
case "+": values.add(part1 + " " + part3 + " " + part2 + " " + " = " + (number1 + number2));
System.out.println(values.get(validNumberExpressions));
validNumberExpressions++;
break;
... //other cases here
}
Ok so here is my issue. I am trying to compare the annual sales of two or more sales reps in an ArrayList and am getting some strange results that I just can't figure out. I have to compare the two, then tell the user how much the rep with the lower sales needs to sell to take the lead. I have it broken into three classes. But I'm pretty sure this act is dependent on just two of those. The first is:
import java.util.ArrayList;
/**
*
* #author Cameron
*/
public class SalesRep {
private ArrayList<CompensationCalculator> pool;
public SalesRep(){
pool = new ArrayList<>();
}
public void setPool(ArrayList<CompensationCalculator> pool){
this.pool = pool;
}
public ArrayList<CompensationCalculator> getPool(){
return pool;
}
public void addToPool(CompensationCalculator salesRep){
pool.add(salesRep);
}
public String toString(String report){
double diff;
for(int i=0; i<pool.size(); i++){
if (pool.get(i).getSales() < pool.get(i++).getSales()){
diff = pool.get(i++).getSales() - pool.get(i).getSales();
report = pool.get(i).getName() + "needs to sell " +
diff + " to take the lead.";
}
if (pool.get(i).getSales() > pool.get(i++).getSales()){
diff = pool.get(i).getSales() - pool.get(i++).getSales();
report = pool.get(i++).getName() + "needs to sell " +
diff + " to take the lead.";
}
}
return report;
}
}
That class should compare the two reps in the array while this one displays it to the user:
import java.util.Scanner;
public class AnnualSales {
public static void main(String[] args){
CompensationCalculator test = new CompensationCalculator(); //Creates a new instance of the class
SalesRep testName = new SalesRep(); //Creates a new instance of the SalesRep class
String cont = new String(); //A string to represent if there ar emore names to be added
Scanner scan = new Scanner(System.in); //Allows for user input to be read
while (!cont.equalsIgnoreCase("n")){
System.out.println("What is the name of the sales representative? ");
test.setName(scan.next());
System.out.println("Please enter " + test.getName() +
"'s annual sales: ");
test.setSales(scan.nextDouble());
testName.addToPool(test);
System.out.println("Are there any more sales representatives you "
+ "would like to add? ");
cont = scan.next();
}
System.out.print(testName.getPool());
System.out.print(testName.toString());
}
}
Now there are no errors being found, the program compiles and executes without a problem. But as a result I get
`[compensationcalculator.CompensationCalculator#55f96302, compensationcalculator.CompensationCalculator#55f96302]compensationcalculator.SalesRep#3d4eac69'
I am extremely confused and have been working on just this method for three hours so I am sure I need a fresh pair of eyes. Any help or guidance would be amazing.
EDIT:
Ok so your suggestion to use a Comparator was deffinetely helpful. I was also confusing myself with unnecessary code so I reworked it a bit and now it is working except for one aspect. Here is the code that I changed:
public String compare(SalesRep rep1, SalesRep rep2){
NumberFormat fmt = NumberFormat.getCurrencyInstance();
Double diff;
if (rep1.getSales() > rep2.getSales()){
diff = rep1.getSales() - rep2.getSales();
return rep2.getName() + " needs to sell " + fmt.format(diff) +
" to take the lead.";}
else{
diff = rep2.getSales() - rep1.getSales();
return rep1.getName() + " needs to sell " + fmt.format(diff) +
" to take the lead.";}
}
I also renamed my classes to better organize them to account for the new requirements. Now the only problem is that it is giving a difference of the two sales as $0.0 no madder what I input. Am I calling on each objects sales incorrectly? I feel like I have run into this problem before but reviewing my past code isn't highlighting what I am doing wrong.
I don't see you call toString(String) but only toString(), that's why you'd get that "stange" output.
Btw, that report parameter of your toString(String) method seems quite odd, since you're not using it besides assignments. You should use a local variable in that case.
Another potential error:
if (pool.get(i).getSales() > pool.get(i++).getSales()){
diff = pool.get(i).getSales() - pool.get(i++).getSales();
report = pool.get(i++).getName() + "needs to sell " +
diff + " to take the lead.";
}
Here you are incrementing i three times, so you'd refer to 3 different indices in pool.
Suppose i = 0, then you'd get:
//the first i++ returns i (0) and then increments i to 1
if (pool.get(0).getSales() > pool.get(0).getSales()){
//here i is 1, thus the next i++ returns 1 and increments i to 2
diff = pool.get(1).getSales() - pool.get(1).getSales();
//here i is 2, so the next i++ returns 2 and increments i to 3
report = pool.get(2).getName() + "needs to sell " +
diff + " to take the lead.";
}
So in that second case you'd add 3 to i and thus advance the loop by 4, since the i++ in the loop's head also increments i once more. I'd suggest you use i + 1 in your loop body instead of i++.
Besides that, your design is quite odd, since class CompensationCalculator actually seems to define a sales rep.
Another thing: I'd probably sort the list of sales reps in descending order (hint: use a Comparator). Then element 0 would be the sales rep with the highest sales and the last element would be the sales rep with the lowest sales. Difference calculations would then be a piece of cake.
The toString that you are calling is the method inherited from Object. The toString method that you defined takes a String parameter.
System.out.print(testName.toString());
so override the proper method.
or use the returned String from your method.
String out;
out = testName.toString(out); // Strings are immutable
Add #override annotation to your toString method and move report in, lie so:
#Override
public String toString(){
String report;
.....
}
Bit of context...
In my project I have one embedded for loop that outputs data whereby for each category show the item and within each item show its property so in reality the output I generated is 3 columns of data in the console (headings: Category/Item/Property) The for loop to show this data looks like this (Variables are set earlier on in the method):
for... (picks up each category)
for...(picks up items in category)
for (String propertyName : item.getPropertyNames()) {
out.println(category.getName() + "\t"
+ itemDesc.getName() + "\tProperty:"
+ propertyName);
}
}
}
The purpose of the project is to provide a more dynamic documentation of the properties of set components in the system. (The /t making it possible to separate them in to individual columns on a console and even in a file in say an excel spreadsheet should I choose to set the file on the printstream (Also at the start of this method.))
The Problem
Now for the problem, after the for loops specified above I have generated another for loop separate from the data but shows the list of all the functions and operators involved in the components:
//Outside the previous for loops
for (Function function : Functions.allFunctions) {
out.println(function.getSignature());
}
What I want is to set this list as the 4th column but the positioning of the for loop and the way it is set leaves it fixed on the first column with the categories. I cant add it after property names as the functions are more generic to everything in the lists and there maybe repetitions of the functions which I am trying to avoid. Is there a way to set it as the forth column? Having trouble finding the sufficient research that specifies what I am looking for here. Hope this makes sense.
One solution, if the total amount of output is small enough to fit in memory, is to simply save all the data into an ArrayList of String, and output it all at the very end.
List<String> myList = new ArrayList<String>();
for... (picks up each category)
for...(picks up items in category)
for (String propertyName : item.getPropertyNames()) {
myList.add(category.getName() + "\t"
+ itemDesc.getName() + "\tProperty:"
+ propertyName);
}
}
}
int i = 0;
// Here we assume that the total lines output by the previous set of loops is
// equal to the total output by this loop.
for (Function function : Functions.allFunctions) {
out.println(myList.get(i) + "\t" + function.getSignature());
i++;
}