Below is the scenario i am trying to automate:
Put all numerical values of the links in a Selenium Weblist & perform an addition and later to verify if the sum of count matches a fixed number.
The issue is that the numerical links returns a number engulfed in braces example:(20)(35)(16)(15)
I need to first trim these brackets & fetch only the numbers & then perform the addition i.e: 20+35+16+15
Later i need to assert the total against the number i.e: Assert.assertequals(sum,'86')
List<WebElement> lists=driver.findElements(By.cssSelector("span.ndocs"));
for (int i=0; i<lists.size(); ){
String trimmed_value=lists.get(i).getText();
trimmed_value=lists.get(i).getText().trim().substring(trimmed_value.indexOf("(") + 1);
trimmed_value=lists.get(i).getText().trim().substring(0, trimmed_value.indexOf(")"));
System.out.println(trimmed_value);
int numerical_value = Integer.parseInt(trimmed_value);
i++;
}
Till now i am able to get the elements, iterate them & able to remove the braces & get the numbers, I am stuck upon how to perform the addition operation & then do an Assert for the count.
Any help will be much appreciated here.
Try using below code.
Initialize a variable outside the method and add every trimmed_value to it as explained below.
import assertEquals(import static org.junit.Assert.assertEquals;)
int expected_value=86;
int numerical_value=0;
List<WebElement> lists = driver.findElements(By.cssSelector("span.ndocs"));
for (int i = 0; i < lists.size(); ) {
String trimmed_value = lists.get(i).getText();
trimmed_value = lists.get(i).getText().trim().substring(trimmed_value.indexOf("(") + 1);
trimmed_value = lists.get(i).getText().trim().substring(0, trimmed_value.indexOf(")"));
System.out.println(trimmed_value);
numerical_value =numerical_value+Integer.parseInt(trimmed_value);
i++;
}
assertEquals(expected_value, numerical_value);
Related
I wrote a for loop that is supposed to determine if there is user input. If there is, it sets the 6 elements of int[] valueArr to the input, a vararg int[] statValue. If there is no input, it sets all elements equal to -1.
if (statValue.length == 6) {
for (int i = 0; i < 6; i++) {
valueArr[i] = statValue[i];
}
} else {
for (int i : valueArr) {
i = -1;
}
}
I am using Visual Studio Code, and it is giving me a message in for (int i : valueArr) :
"The value of the local variable i is not used."
That particular for loop syntax is still new to me, so I may be very well blind, but it was working in another file:
for(int i : rollResults) {
sum = sum + i;
}
I feel that I should also mention that the for loop giving me trouble is in a private void method. I'm still fairly new and just recently started using private methods. I noticed the method would give the same message when not used elsewhere, but I do not see why it would appear here.
I tried closing and reopening Visual Studio Code, deleting and retyping the code, and other forms of that. In my short experience, I've had times where I received errors and messages that should not be there and fixed them with what I mentioned, but none of that worked here.
for (int i : valueArr) {
.... CODE HERE ...
}
This sets up a loop which will run CODE HERE a certain number of times. Inside this loop, at the start of every loop, an entirely new variable is created named i, containing one of the values in valueArr. Once the loop ends this variable is destroyed. Notably, i is not directly the value in valueArr - modifying it does nothing - other than affect this one loop if you use i later in within the block. It does not modify the contents of valueArr.
Hence why you get the warning: i = -1 does nothing - you change what i is, and then the loop ends, which means i goes away and your code hasn't changed anything or done anything, which surely you didn't intend. Hence, warning.
It's not entirely clear what you want to do here. If you intend to set all values in valueArr to -1, you want:
for (int i = 0; i < valueArr.length; i++) valueArr[i] = -1;
Or, actually, you can do that more simply:
Arrays.fill(valueArr, -1);
valueArr[i] = -1 changes the value of the i-th value in the valueArr array to -1. for (int i : valueArr) i = -1; does nothing.
As part of a program that generates a text output file, I need to insert a predefined number n (which corresponds to the number of required elements) and automatically create conditions among them.
E.g. for n=3, the elements s1, s2 and s3 are generated. What I want to achieve is to generate the following conditions automatically and print them in a text file:
s1<s2 & s1<s3
s2<=s1 & s2<s3
s3<=s1 & s3<=s2
The above conditions cover all possible combinations between the elements. What I have so far is an ArrayList that holds as many elements as the predefined number n and the following code to produce the required results:
int counter = 0;
ArrayList<String> state = new ArrayList<String>();
for (int i=0; i<=n; i++) {
state.add(i,"s"+1));
}
for (int j=1; j<=n; j++) {
for (int i=0; i<(n-1); i++) {
if (i==(n-2)) {
fw.write(state.get(i)+"<"+state.get(counter));
}
else {
fw.write(state.get(i)+"<"+state.get(counter)+" & ");
}
}
counter++;
}
I know that using the counter in this case is not correct, but I cannot think of a way to correctly represent the different conditions.
UPDATE:
Using the following code for testing purposes I managed to get close to the desired outcome:
ArrayList<String> collectStates = new ArrayList<String>();
String activeState,writtenState;
for (int i=0; i<n; i++) {
for (int j=0; j<state.size(); j++) {
if (state.get(i) != state.get(j)) {
activeState=state.get(i)+"<"+state.get(j);
writtenState=state.get(j)+"<"+state.get(i);
if (collectStates.contains(activeState)) {
System.out.print(state.get(i)+"<="+state.get(j));
}
else {
System.out.print(activeState);
}
if (j!=state.size()-1) {
System.out.print(" & ");
}
collectStates.add(writtenState);
}
}
System.out.print("\n");
}
The output I receive is:
s1<s2 & s1<s3
s2<=s1 & s2<s3
s3<=s1 & s3<=s2 &
The only problem is the extra & at the end of the last line, which I don't know yet how to fix.
I found the answer to my question! In the updated section of the description I performed the following addition to remove the extra & symbol:
Old version:
if (j!=state.size()-1) {
System.out.print(" & ");
}
Updated version:
if ((j!=state.size()-1) && ((j!=state.size()-2) || (i!=state.size()-1))) {
fw.write(" & ");
}
The problem appeared always in the last row of the output conditions, thus the newest fix. The output is now exactly as described in the description.
In further detail, what the program did is to remove the identical values:
s1?s1 & s1?s2 & s1?s3
s2?s1 & s2?s2 & s2?s3
s3?s1 & s3?s2 & s3?s3
So by removing:
s1?s1 & we keep s1?s2 & s1?s3
s2?s2 & we keep s2?s1 & s2?s3
s3?s3 we keep s3?s1 & s3?s2 &
As a result, the addition of the new condition is necessary to remove the extra & in the last row.
I am working on a Displaykeyboard for disabled peaople and i am thinking about to adding a auto word completion function.
I found a example from oracle that works as i need it. Its the Another Example: TextAreaDemo. The problem is i dont really understand the search algorithm and the problem is when i add some word to the arraylist the search algorithm stops working properly.
String prefix = content.substring(w + 1).toLowerCase();
int n = Collections.binarySearch(words, prefix);
if (n < 0 && -n <= words.size()) {
String match = words.get(-n - 1);
if (match.startsWith(prefix)) {
// A completion is found
String completion = match.substring(pos - w);
// We cannot modify Document from within notification,
// so we submit a task that does the change later
SwingUtilities.invokeLater(
new CompletionTask(completion, pos + 1));
}
} else {
// Nothing found
mode = Mode.INSERT;
}
Is there a way to modify the example so it will work with any words?
Make sure you're not just adding the word to the end of the list and then using binarySearch(). It's documentation says the following
The list must be sorted into ascending order according to the natural
ordering of its elements (as by the sort(List) method) prior to making
this call.
Read more about it here: https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#binarySearch(java.util.List,%20T)
My requirement is to generate 1000 unique email-ids in Java. I have already generated random Text and using for loop I'm limiting the number of email-ids to be generated. Problem is when I execute 10 email-ids are generated but all are same.
Below is the code and output:
public static void main() {
first fr = new first();
String n = fr.genText()+"#mail.com";
for (int i = 0; i<=9; i++) {
System.out.println(n);
}
}
public String genText() {
String randomText = "abcdefghijklmnopqrstuvwxyz";
int length = 4;
String temp = RandomStringUtils.random(length, randomText);
return temp;
}
and output is:
myqo#mail.com
myqo#mail.com
...
myqo#mail.com
When I execute the same above program I get another set of mail-ids. Example: instead of 'myqo' it will be 'bfta'. But my requirement is to generate different unique ids.
For Example:
myqo#mail.com
bfta#mail.com
kjuy#mail.com
Put your String initialization in the for statement:
for (int i = 0; i<=9; i++) {
String n = fr.genText()+"#mail.com";
System.out.println(n);
}
I would like to rewrite your method a little bit:
public String generateEmail(String domain, int length) {
return RandomStringUtils.random(length, "abcdefghijklmnopqrstuvwxyz") + "#" + domain;
}
And it would be possible to call like:
generateEmail("gmail.com", 4);
As I understood, you want to generate unique 1000 emails, then you would be able to do this in a convenient way by Stream API:
Stream.generate(() -> generateEmail("gmail.com", 4))
.limit(1000)
.collect(Collectors.toSet())
But the problem still exists. I purposely collected a Stream<String> to a Set<String> (which removes duplicates) to find out its size(). As you may see, the size is not always equals 1000
999
1000
997
that means your algorithm returns duplicated values even for such small range.
Therefore, you'd better research already written email generators for Java or improve your own (for example, by adding numbers, some special characters that, in turn, will generate a plenty of exceptions).
If you are planning to use MockNeat, the feature for implementing email strings is already implemented.
Example 1:
String corpEmail = mock.emails().domain("startup.io").val();
// Possible Output: tiptoplunge#startup.io
Example 2:
String domsEmail = mock.emails().domains("abc.com", "corp.org").val();
// Possible Output: funjulius#corp.org
Note: mock is the default "mocking" object.
To guarantee uniqueness you could use a counter as part of the email address:
myqo0000#mail.com
bfta0001#mail.com
kjuy0002#mail.com
If you want to stick to letters only then convert the counter to base 26 representation using 'a' to 'z' as the digits.
I am currently trying to make a naming convention. The idea behind this is parsing.
Lets say I obtain an xml doc. Everything can be used once, but these 2 in the code below can be submitted several times within the xml document. It could be 1, or simply 100.
This states that ItemNumber and ReceiptType will be grabbed for the first element.
ItemNumber1 = eElement.getElementsByTagName("ItemNumber").item(0).getTextContent();
ReceiptType1 = eElement.getElementsByTagName("ReceiptType").item(0).getTextContent();
This one states that it will grab the second submission if they were in their twice.
ItemNumber2 = eElement.getElementsByTagName("ItemNumber").item(1).getTextContent();
ReceiptType2 = eElement.getElementsByTagName("ReceiptType").item(1).getTextContent();
ItemNumber and ReceiptType must both be submitted together. So if there is 30 ItemNumbers, there must be 30 Receipt Types.
However now I would like to set this in an IF statement to create variables.
I was thinking something along the lines of:
int cnt = 2;
if (eElement.getElementsByTagName("ItemNumber").item(cnt).getTextContent();)
**MAKE VARIABLE**
Then make a loop which adds one to count to see if their is a third or 4th. Now here comes the tricky part..I need them set to a generated variable. Example if ItemNumber 2 existed, it would set it to
String ItemNumber2 = eElement.getElementsByTagName("ItemNumber").item(cnt).getTextContent();
I do not wish to make pre-made variable names as I don't want to code a possible 1000 variables if that 1000 were to happen.
KUDOS for anyone who can help or give tips on just small parts of this as in the naming convention etc. Thanks!
You don't know beforehand how many ItemNumbers and ReceiptTypes you'll get ? Maybe consider using two Lists (java.util.List). Here is an example.
boolean finished = ... ; // true if there is no more item to process
List<String> listItemNumbers = new ArrayList<>();
List<String> listReceiptTypes = new ArrayList<>();
int cnt = 0;
while(!finished) {
String itemNumber = eElement.getElementsByTagName("ItemNumber").item(cnt).getTextContent();
String receiptType = eElement.getElementsByTagName("ReceiptType").item(cnt).getTextContent();
listItemNumbers.add(itemNumber);
listReceiptTypes.add(receiptType);
++cnt;
// update 'finished' (to test if there are remaining itemNumbers to process)
}
// use them :
int indexYouNeed = 32; // for example
String itemNumber = listItemNumbers.get(indexYouNeed); // index start from 0
String receiptType = listReceiptTypes.get(indexYouNeed);