Search element in array - arrays

I'm creating an Address Book program using array. I've done with the add and print data option. But now I'm stuck with the search/update option.
This is my code in searching for the element if it exist in my array or not.
public void update_data(){
String user_input_data;
int search_data = 0;
System.out.println("Enter the data that you want to search: ");
user_input_data = user_data.nextLine();
while(search_data<data_recorded){
if(user_input_data == AddressBook_Array_name[search_data])
{
System.out.println("Data found!");
}
else
{
System.out.println("Data not found!");
}
search_data++;
}
}
But when I run the program. It always return to false and print the else statement.
I don't know what's wrong with it. Anyway the data_recorded variable holds the number of data inputted by the user in the add option.

You need to use equals() instead of == in java for comparision.
if (user_input_data.equals(AddressBook_Array_name[search_data]))
Also, instead of the while you may want to use the foreach loop (removes the need for search_data variable).
for(String addressBookElem : AddressBook_Array_name) {
if (user_input_data.equals(addressBookElem)) {
System.out.println("Data found!");
return;
}
}
System.out.println("Data not found!"); // reaches this statement if data not present

i think you should use .equals function instead of ==.

Related

for loop returns only the first data

I am trying to loop through my database and returns all the data. The query returns all the data in the database but when I try to loop through it one after the other, it only check the first data and then terminate even when the second or third data might be true.
I don't know the error that I made.
public List<CardType> getAllAvailableCardType(){
List<CardType> cardTypeList = cardTypeRepository.findAll();
//this method returns a list of all the cardType from the db
//and it's working perfectly
return cardTypeList;
}
public void getCards(String cardType) throws DataNotFoundException {
String cardName = "";
List<CardType> cardTypeList = getAllAvailableCardType();
for (CardType cardTypes: cardTypeList){
//loop through the list
if (cardType.equalsIgnoreCase(cardTypes.getCardTypeName())){
//check if the entered string correspond with any of the cardTypeName in the db
//I have upto five cardNames stored in my db
//if it's true, log it in a console else through the other exception
log.info("Congrats, there is card with the entered name "+cardType);
}
throw new DataNotFoundException("There is no card with such name");
}
//the problem I am facing is that this doesn't loop through my db
//it only check if the condition is true or not only on the first data in the db
}
I believe its because you are throwing a datanotfound exception inside the loop, so after the first check in the IF statement if not met then it will go to the last line in the loop which is throw an exception, try the below refactored code
public void getCards(String cardType) throws DataNotFoundException {
String cardName = "";
List<CardType> cardTypeList = getAllAvailableCardType();
boolean found = false;
for (CardType cardTypes: cardTypeList){
//loop through the list
if (cardType.equalsIgnoreCase(cardTypes.getCardTypeName())){
//check if the entered string correspond with any of the cardTypeName in the db
//I have upto five cardNames stored in my db
//if it's true, log it in a console else through the other exception
log.info("Congrats, there is card with the entered name "+cardType);
found = true;
break;
}
}
if (!found) {
throw new DataNotFoundException("There is no card with such name");
}
}

I am trying to automate dropdown list in selenium web driver using Page object model. Below is my code explanation:

// Language Selection
public static void SelectLanguage() {
waitForElementToBeClickable(driver.findElement(By.xpath("//div[#class=\"lang-identifier\"]")));
driver.findElement(By.xpath("//div[#class=\"lang-identifier\"]")).click();
List<WebElement> elements = driver.findElements(By.xpath("//ul[#class=\"dropdown-menu pull-right\"]/li"));
for (WebElement e : elements) {
String text = e.getAttribute("value");
System.out.println(e.getText());
if (text.equalsIgnoreCase("English")) {
e.click();
break;
} else if (e.getText().equalsIgnoreCase("Español")) {
e.click();
break;
} else if (e.getText().equalsIgnoreCase("Italiano")) {
e.click();
break;
} else if (e.getText().equalsIgnoreCase("Pусский")) {
e.click();
break;
} else if (e.getText().equalsIgnoreCase("Français")) {
e.click();
break;
} else if (e.getText().equalsIgnoreCase("Português")) {
e.click();
break;
} else {
System.out.println("Please select appropriate language");
}
}
}
I would suggest a much simpler but more flexible version of your method.
Some suggestions:
I would change your method to take the desired language as a parameter to significantly simplify the code but also make it very flexible.
WebDriverWait, in most cases, will return the found element(s). Use that to simplify your code to a one-liner, e.g.
new WebDriverWait(...).until(ExpectedConditions.elementToBeClickable).click();
You didn't provide the code of your custom method, waitForElementToBeClickable, but if you really want to keep it, have it return the element(s) waited for to make it more useful and save having to write extra code.
If you have nested double quotes, I would suggest you use a combination of double and single quotes. It's a personal preference but I think it makes it easier to read than \", e.g.
"//div[#class=\"lang-identifier\"]"
would turn into
"//div[#class='lang-identifier']"
Instead of grabbing all options and then looping through them to compare the contained text to some desired string, use an XPath that contains the desired text instead, e.g. for "English" the XPath will look like
//ul[#class='dropdown-menu pull-right']/li[text()='English']
NOTE: .getAttribute("value") gets the value of an INPUT and will not work on other elements, e.g. the LI elements in your elements variable. .getText() returns the text contained in an element but will not work on INPUTs.
After implementing these suggestions, the code turns into a two-liner and is very flexible.
public static void SelectLanguage(String language) {
new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.cssSelector("div.lang-identifier"))).click();
driver.findElement(By.xpath("//ul[#class='dropdown-menu pull-right']/li[text()='" + language + "']")).click();
}

My strcmp doesn't return 0 when it should

Context : I'm searching for all the words contained in a 2d array (horizontally,vertically and diagonaly).
So what I do is I get all the possible words, check if they're in the given dictionary and if they are store them in an array. The thing is, I don't want it to have duplicates.
Here's a snippet of the code:
for (i=l-1;i>=0;i--){
palavra[aux]=mat[i][caux];
for (j=i;j>=0;j--){
palavra[aux]=mat[j][caux];
palavra[aux+1]='\0';
for (it=0;encontradas[it]!=NULL;it++){
if (strcmp(palavra,encontradas[it])==0)flag=1;
else flag=0;
}
if (flag==0) {
r = palavra_existe(dic,palavra);
if (r!=0) {
found[auxenc]=mystrdup(palavra);
auxenc++;
}
}
flag=0;
aux++;
}
aux=0;
}
The
if (strcmp(palavra, found[it])==0)flag=1
line is there to check if the formed worded has been found already, to avoid creating a duplicate. The problem is it doesn't work, duplicates appear anyway (as the flag variable never takes the value 1).
What could I be missing here?
The flag variable does get the value 1, but then it turns back to 0 again in the next iteration.
Set flag to zero before the loop, and when you find a match you set it to 1 and exit the loop:
flag = 0;
for (it = 0; encontradas[it] != NULL; it++) {
if (strcmp(palavra,encontradas[it]) == 0) {
flag=1;
break;
}
}
(Exiting the loop isn't needed for the logic to work, but there is no point in looping through the rest of the items once you have found a match.)

How to use verifyText for comparing two strings?

As we know, assert continues the execution but verify stops the execution the moment the script fails.
e.g suppose two string abc, abd xyz
i want to verify the two strings. How to verify them without using Assert.assertEquals(expected, actual);
Can anyone please guide me for the same?
You can verify the 2 strings by creating a method and using if else to compare them.
In your example instead of assert this can be done
public void compareMethod()
{
string expected = "abc";
string actual = "xyz";
if(expected == actual)
{
//do steps required
}
else
{
}
}
If you have already stored strings and want to verifyText using Selenium WebDriver then the following code will surely help..
if("expected String".equals("actual string"))
{
System.out.println("String matches ");
}
else
{
System.out.println("String does not match ");
}
Try this

Delete records using integer list

I want to Loop through the array of integers and want to remove the items in the TLToProcess list which i have stored in the array of integers
here is the code
I want to remove only the selected in the list integer
iSize.add(TLToProcess.size());
if(TLToProcess[i].Scan_In1__c==null)
{
if(TLToProcess[i].typew__c=='Pending')
{
TLForMissingHHhh.add(TLToProcess[i]);
}
}
else if ( c[i].Scan_In1__c!=null)
{
if (TLToProcess[i].typew__c=='Pending' )
{
TLToProcess[i].typew__c='Processed';
}
}
}
Now i want to remove record 1 by 1 from TLToProcess using
remove() can any body tell me how to do it.
Thanks
Anu
Not sure I understand your problem, but if what you're trying to avoid is modifying your List of integers inside a loop and getting this error: {"Collection was modified; enumeration operation may not execute."} you can create a copy of your List(.ToList()) and use it to iterate, and this way you can call Remove() safely.
List<Int32> arr = new List<Int32>();
for (int i = 0; i < 10; i++)
{
arr.Add(i);
}
foreach(var o in arr.ToList())
{
arr.Remove(o);
}
Is that the intent?

Resources