Not FInding String Match With Contains- Java - java

running into a problem.
The code is not finding the string that equals 8QQ which is a match
here is my full code.
String selector = "div#companyIdBarCompListGrid_rows_scrollpane table tbody tr[id*=companyIdBarCompListGrid_] td span div a";
int links = driver.findElements(By.cssSelector(selector)).size();
System.out.println("Number of links: " + links);
// begin inner for-loop
for (int i = 0; i < links; i++) {
PP_OBJ_CycleData.ScrollToTop(driver);// scroll up
List<WebElement> CCTable = driver.findElements(By.cssSelector(selector));
WebElement code = CCTable.get(i);
System.out.println("\n"+code.getText().substring(0, 3).trim()+"\n");
//code.click();
//----------------------checking for bad code -----------------------------------------
String[] badcodes = {"8QQ", "8BQ", "8JQ"};
boolean check = Arrays.asList(badcodes).contains(code);
System.out.println(check);
//check == true will work as well
if(check){
System.out.println(check+"Bad Code found breaking loop");
break;
}else{
//checking to make sure element is clickable
PP_OBJ_CycleData.isClickable(code, driver);
System.out.println("Clickable?"+ code.isEnabled());
code.click();
}
I think the problem is this part here:
List<WebElement> CCTable = driver.findElements(By.cssSelector(selector));
WebElement code = CCTable.get(i);
System.out.println("\n"+code.getText().substring(0, 3).trim()+"\n");
//code.click();
I am cutting off everything but the first 3 characters with sub string but that is during the print statement. however the string is actually longer or has more characters than what is in the array for 8QQ. Could this be the problem if so is there a way to get around it? So that it only tries to match the first 3 characters? the.contains() is not doing it i don't think.
I saw matches.find() methods but have not had any success.
This is my code now it works had to think about it for a long time my code is below. and now it breaks loop.
String selector = "div#companyIdBarCompListGrid_rows_scrollpane table tbody tr[id*=companyIdBarCompListGrid_] td span div a";
int links = driver.findElements(By.cssSelector(selector)).size();
System.out.println("Number of links: " + links);
// begin inner for-loop
for (int i = 0; i < links; i++) {
PP_OBJ_CycleData.ScrollToTop(driver);// scroll up
List<WebElement> CCTable = driver.findElements(By.cssSelector(selector));
WebElement code = CCTable.get(i);
// changing code to mcode to look for first 3 characters
String mcode = code.getText().substring(0, 3).trim();
System.out.println("\n"+ "modified "+ mcode);
// System.out.println("\n"+code.getText().substring(0, 3).trim()+"\n");
//----------------------checking for bad code -----------------------------------------
String[] badcodes = {"8QQ", "8BQ", "8JQ"};
boolean check = Arrays.asList(badcodes).contains(mcode);
System.out.println(check+"code in array list");
//check == true will work as well
if(check){
System.out.println(check+"-Bad Code found breaking loop");
break;
}else{
//checking to make sure element is clickable
PP_OBJ_CycleData.isClickable(code, driver);
System.out.println("Clickable?"+ code.isEnabled());
code.click();
}

There are two problems with your code
Arrays.asList(badcodes) returns a List<String>, while code is a WebElement: you're comparing two different types, so check will never be true
You say that code is more than three characters, but List.contains expects equality.
You might be confusing String.contains and List.contains.
myString.contains(code) will return true if code is a substring of the String myString
myList.contains(code) will return true if code is an element of the List myList
In your code, Arrays.asList(badcodes).contains(code) calls List.contains, and returns false because - as you say - code is longer than any of the Strings you're comparing to.
How do you fix it?
Convert code to a String. You should know how to do that, because you already do it in the System.out.println above.
Ensure code has the same length as the strings you're comparing to. You should know how to do that, because you already do it in the System.out.println above.

Related

Selenium-Get list index number based on text match

Automation scenario is to get all the links in weblist & then get this arraylist content outside loop and then get the index number dynamically based on the url hit.
String values="";
List<WebElement> url_link = driver.findElements(By.cssSelector(".anomaly>a"));
for ( WebElement we: url_link) {
String temp = values;
values = temp + we.getText();
}
System.out.println("Text "+values);
int ind=values.indexOf("www.test.com");
System.out.println("Index "+ind);
The above code returns me a weird index number of 74.
The url_link output contents are:
wwww.hatch.com
wwww.tist.com
wwww.helix.com
wwww.patching.com
wwww.seyh.com
wwww.test.com
wwww.toast.com
wwww.telling.com
wwww.uity.com
so based upon the expected result i am expecting the index number to be 5.
Any help will be appreciated.
The variable values is a variable of type String, it's not a List. So when you do values = temp + we.getText();, you are basically appending all the links in a single String. So the output will actually be this:
wwww.hatch.comwwww.tist.comwwww.helix.comwwww.patching.comwwww.seyh.comwwww.test.comwwww.toast.comwwww.telling.comwwww.uity.com
The index of www.test.com is 74 in this string. You should be adding these links in an ArrayList and then find the index of the link you want to search.
Something like this should work:
List<String> values = new ArrayList<String>();
List<WebElement> url_link = driver.findElements(By.cssSelector(".anomaly>a"));
for ( WebElement we: url_link) {
values.add(we.getText());
}
int ind = values.indexOf("www.test.com");
System.out.println("Index "+ind);

Java: I compare two Strings but it didn't recognize it

I have this problem:
I wrote this function because I need to get the index of the occurrence of a particular string st in a String array
static public int indicestring(String[] array, String st) {
int ret = -1;
for (int i = 0; i < array.length; i++){
if (st.equals(array[i])) {
ret=i;
break;
}
}
return ret;
}
I then called:
System.out.println("indicestring(NODO,"ET2"));
and I got the correct number.
But then when I do:
String[] arcos2 = linea.split("-");//reading from a file and separating by "-"
String aux = arcos2[1];
System.out.println(arcos2[1]);
System.out.println(aux);
if (aux.equals(arcos2[1])) {
System.out.println("Is equal 1");
}
if (aux.equals("ET2")) {
System.out.println("Is equal 2");
}
if ("ET2".equals(aux)) {
System.out.println("is equal 3");
}
The first two prints were ET2, but then it only printed of the 3 ifs is "Is equal 1".... The thing is I have nearly 200 nodes like "ET2" and only 3 are failing and giving me -1 in the first function...
My question is....Am I using wrong the arrays to save and compare the data, because if aux=arcos2[1]="ET2", why is 'aux.equals("ET2") 'or 'arcos2[1].equals("ET2)' not working
? Is ther another function you can recommend to try?(I tried changing equals with compareTo() == 0 and that didn't work either and trimming was also recommended).
Before, I had a similar error where I compare two arrays like this:
if(a[0] == b[0] && a[1] == b[1])
There was a case that clearly was correct but it was ignored...
But it got corrected when a i changed it to:
if (Arrays.equals(a, b))
Is there maybe some change like that
You should put a debug break point in the code and add expression watches to identify the root cause of the problem.

How would I check if a part of a string equals another string of unknown length?

for(int j = 1;j<fileArray.size();j++) {
if(str.contains(fileArray.get(end+j))) {
}
}
(assume end is some number such as 30).
The goal of this part is when having a window length of 30 and a fileArray size > 30, check if theres anything after index 30 that matches whatever is inside the window.
ex: "i like to eat piesss aaaabbbbpiesssbbbb"
starting from the beginning of the string add the first 17 characters to a arraylist called window. then i check the rest of the string starting from right after window to see if there's anything that matches. space doesnt match so you add it to the output. keep checking then you see "piesss" matches. Then i replace the second "piesss" with wherever the first "piesss" occurs.
So right now im using fileArray.get(end+j) to check if there's anything that matches within my string(str) except this doesn't really work. Is there a way I could fix this code segment?
The replacement part of your question is still unclear. As is any reasoning to use an ArrayList. I've written some code that does a 5 character window search for a match after splitting the string you provided. Note how with the 30 and 17 values you gave nothing is ever matched (see commented out code). However with tweaked values some matches can be found.
public static void main(String[] args) {
// 1 2 3
//012345678901234567890123456789012345678 <- shows the index
String test = "i like to eat piesss aaaabbbbpiesssbbbb";
// int first = 17;
// int end = 30;
int first = 20;
int end = 37;
String firstHalf = test.substring(0, first);
String secondHalf = test.substring(first, end);
int matchSize = 5;
for (int i = 0; i + matchSize < secondHalf.length() ; i++)
{
String window = secondHalf.substring(i, i + matchSize);
if ( firstHalf.contains(window) )
{
System.out.println(window);
}
}
System.out.println("Done searching.");
}
Displays:
piess
iesss
Done searching.
If this isn't what you meant PLEASE edit your question to make your needs clear.

Dynamic AND conditions in an if statement

I have an input String that contains a couple of search terms to find a line in a text including all of the search terms.
For example:
String searchTerms = "java stackoverflow conditions";
String [] splittedTerm = searchTerms.split(" ");
The search terms are AND connective:
if (textLine.contains(splittedTerm[0] && textLine.contains(splittedTerm[1]) && textLine.contains(splittedTerm[2])) start=true;
But the number of search terms is dynamic, it alwayse depends on the users request...
So is there any possibility to use the if statement depending on the number of search terms?
You need to loop through the String[] that you get after splitiing the String :-
First add all the elements you want to compare in an array, then iterate and compare through first array and array returned from split(). Make sure both arrays are of equal length
boolean flag=true;
String searchTerms = "java stackoverflow conditions hello test";
String [] splittedTerm = searchTerms.split(" ");
for(int i=0;i<splittedTerm.length;i++){
if (!(textLine[i].equals(splittedTerm[i]))){ //textLine is the array containing String literals you want to compare.
flag=false;
}
}
start=flag;
you could do a loop which iterates over all search terms. If any missmatch is found, set a flag and break the loop. Below the loop you can then check the flag, if it's still true all of your search terms matched.
boolean flag = true;
for (String searchTerm : splittedTerm){
if (!stringToSearch.contains(searchTerm) {
flag = false;
break;
}
}
if (flag)
all terms matched
else
one or more terms did not match

Search array for value containing all characters(in any order) and return value

I've searched high and low and finally have to ask.
I have an array containing, for example, ["123456","132457", "468591", ... ].
I have a string with a value of "46891".
How do I search through the array and find the object that contains all the characters from my string value? For example the object with "468591" contains all the digits from my string value even though it's not an exact match because there's an added "5" between the "8" and "9".
My initial thought was to split the string into its own array of numbers (i.e. ["4","6","8","9","1"] ), then to search through the array for objects containing the number, to create a new array from it, and to keep whittling it down until I have just one remaining.
Since this is likely a learning assignment, I'll give you an idea instead of an implementation.
Start by defining a function that takes two strings, and returns true if the first one contains all characters of the second in any order, and false otherwise. It should looks like this:
boolean containsAllCharsInAnyOrder(String str, String chars) {
...
}
Inside the function set up a loop that picks characters ch from the chars string one by one, and then uses str.indexOf(ch) to see if the character is present in the string. If the index is non-negative, continue; otherwise, return false.
If the loop finishes without returning, you know that all characters from chars are present in src, so you can return true.
With this function in hand, set up another loop in your main function to go through elements of the array, and call containsAllCharsInAnyOrder on each one in turn.
I think you can use sets for this.
List<String> result = new ArrayList<>();
Set<String> chars = new HashSet<>(Arrays.asList(str.split(""));
for(String string : stringList) {
Set<String> stringListChars = new HashSet<>(Arrays.asList(string.split(""));
if(chars.containsAll(stringListChars)) {
result.add(string);
}
}
There is a caveat here; it doesn't work as you would expect for repeated characters and you haven't specified how you want to handle that (for example, 1154 compared against 154 will be considered a positive match). If you do want to take into account repeated characters and you want to make sure that they exist in the other string, you can use a List instead of a Set:
List<String> result = new ArrayList<>();
List<String> chars = Arrays.asList(str.split(""));
for(String string : stringList) {
List<String> stringListChars = Arrays.asList(string.split("");
if(chars.containsAll(stringListChars)) {
result.add(string);
}
}
Your initial idea was good start, so what you can do is to create not an array but set, then using Guava Sets#powerSet method to create all possible subsets filter only those that have "46891".length mebers, convert each set into String and look those strings in the original array :)
You could do this with the ArrayList containsAll method along with asList:
ArrayList<Character> lookingForChars = new ArrayList<Character>(Arrays.asList(lookingForString.toCharArray()));
for (String toSearchString : array) {
ArrayList<Character> toSearchChars = new ArrayList<Character>(Arrays.asList(toSearchString.toCharArray));
if (toSearchChars.containsAll(lookingForChars)) {
System.out.println("Match Found!");
}
}
You can use String#chartAt() in a nested for loop to compare your string with each of the array's elements.
This method would help you check whether a character is contained in both strings.
This is more tricky then a straigt-forward solution.
The are better algorithms but here one easy to implement and understand.
Ways of solving:
Go through every char at your given string and check if it at the
given arrray.
Collect list for every string from the selected
array containing the given char.
Check if no other char to check.
If there is, Perform A again but on the collected list(result list).
Else, Return all possible matches.
try this
public static void main(String args[]) {
String[] array = {"123456", "132457", "468591"};
String search = "46891";
for (String element : array) {
boolean isPresent = true;
for (int index = 0; index < search.length(); index++) {
if(element.indexOf(search.charAt(index)) == -1){
isPresent = false;
break;
}
}
if(isPresent)
System.out.println("Element "+ element + " Contains Serach String");
else
System.out.println("Element "+ element + " Does not Contains Serach String");
}
}
This sorts the char[]'s of the search string and the and the string to search on. Pretty sure (?) this is O(n logn) vs O(n^2) without sorting.
private static boolean contains(String searchMe, String searchOn){
char[] sm = searchMe.toCharArray();
Arrays.sort(sm);
char[] so = searchOn.toCharArray();
Arrays.sort(so);
boolean found = false;
for(int i = 0; i<so.length; i++){
found = false; // necessary to reset 'found' on subsequent searches
for(int j=0; j<sm.length; j++){
if(sm[j] == so[i]){
// Match! Break to the next char of the search string.
found = true;
break;
}else if(sm[j] > so[i]){ // No need to continue because they are sorted.
break;
}
}
if(!found){
// We can quit here because the arrays are sorted.
// I know if I did not find a match of the current character
// for so in sm, then no other characters will match because they are
// sorted.
break;
}
}
return found;
}
public static void main(String[] args0){
String value = "12345";
String[] testValues = { "34523452346", "1112", "1122009988776655443322",
"54321","7172839405","9495929193"};
System.out.println("\n Search where order does not matter.");
for(String s : testValues){
System.out.println(" Does " + s + " contain " + value + "? " + contains(s , value));
}
}
And the results
Search where order does not matter.
Does 34523452346 contain 12345? false
Does 1112 contain 12345? false
Does 1122009988776655443322 contain 12345? true
Does 54321 contain 12345? true
Does 7172839405 contain 12345? true
Does 9495929193 contain 12345? true

Categories