Java Webdriver count first name without last name - java

I'm writing a selenium webdriver java test and trying to count the number of names that appear without the last name following it.
For example, any time "John Smith" appears, it wouldn't be counted, but if it was a sentence like "John did this", since Smith didn't appear, it would increase the count.
Unfortunately at this point, trying to read/count from a WebElement is returning a 0 no matter what I do, but I know either way I wouldn't be excluding the last name entries. Any suggestions welcome!
Current code:
//get string from WebElement text
`String john = JohnSmith.getText();
int johnCount =0;
while (john.contains("john")){
johnCount++;
//this line starts from the substring after the first john
john = john.substring(john.indexOf("john") + "john".length());
}

My first thought is to do something simple like replace "John Smith" with "" and then count the instances of "John". One simple way to count the instances is to split the string using "John" and count them.
A simple example:
String s = "This is John Smith. John is walking in the park. John likes coffee. His name is John Smith.";
s = s.replaceAll("John Smith", "");
int count = s.split("John").length - 1;
System.out.println(count); // 2
EDIT:
... or better yet, turn it into a function that can be reused easily...
public int countFirstNames(String firstName, String lastName, String searchText)
{
searchText = searchText.replace(firstName + " " + lastName, "");
return searchText.split("John").length - 1;
}
and call it like
String s = "This is John Smith. John is walking in the park. John likes coffee. His name is John Smith.";
System.out.println(countFirstNames("John", "Smith", s)); // 2

Related

Splitting a String with different inputs Java

Input = computer science: harvard university, cambridge (EXAMPLE)
Prompt: Use a String method twice, to find the locations of the colon and the comma.
Use a String method to extract the major and store it into a new String.
Use a String method to extract the university and store it into a new String.
Use a String method to extract the city and store it into a new String.
Display the major, university, and city in reverse, as shown below, followed by a newline.
I was thinking I could just use substring(); but the input entered from the user varies and so the indexes are all different. I am still learning and am stumped on how to do this one. Does substring let you somehow use it without knowing the specific index? Or do I have to use a whole different method? Any help would be awesome. BTW this is HW.
Assuming the input string has format: <major>: <university>, <city>
String has a set of indexOf() methods to find the position of a character/substring (returns -1 if the character/substring is not found) and substring to retrieve a subpart of the input from index or between a pair of indexes.
Also, String::trim may be used to get rid of leading/trailing whitespaces.
String input = "computer science: harvard university, cambridge";
int colonAt = input.indexOf(':');
int commaAt = input.indexOf(',');
// or int commaAt = input.indexOf(',', colonAt + 1); to make sure comma occurs after the colon
String major = null;
String university = null;
String city = null;
if (colonAt > -1 && commaAt > -1) {
major = input.substring(0, colonAt);
university = input.substring(colonAt + 1, commaAt).trim();
city = input.substring(commaAt + 1).trim();
}
System.out.printf("Major: '%s', Univ: '%s', City: '%s'%n", major, university, city);
Output:
Major: 'computer science', Univ: 'harvard university', City: 'cambridge'

Splitting a String and then displaying a portion of that split (last name part)

Hey I'm having an issue with the following problem. I understand how to split the formalName variable (a first " " last name) but now I'm having trouble just displaying the last name so I can generate the formalName ("Mr./Ms. " lastName) can anyone help?
Complete the generateFormalName method so that… you return the formal
name (Mr. or Ms. + last name) given a full name and gender (Strings)
as parameters.
--You can assume a valid name & gender (any case allowed) is passed in. Example 1: ("Bob Smith", "MaLE") passed in should generate "Mr.
Smith" Example 2: ("Maggie May", "feMALE") passed in should generate
"Ms. May"
Tip 1: You are given a String formalName initialized to the empty
String -- you will want to concatenate other Strings onto this to
produce the full formalName.
Tip 2: Write your algorithm in English first.
Tip 3: Think of all of the methods at your disposal and which could be
helpful.
split() function returns you an array of strings. You need to get second element from the array. You can try something like this:
String fullName = "John Smith";
String lastName = fullName.split(" ")[1];
String formalName = "Mr./Ms. " + lastName;

Last two letters of a user inputted string using substring (Java)

I'm writing a program that generates star wars names. The user inputs their first, last, mother's maiden name, birth city, and first car and the program gives a star wars name. I need the last two characters* of the user inputted last name. I know I can use substring, but I cannot get anything to work. The best I have is:
lastname.substring(lastname.length() -2)
which gives the first two letters of the last name, and not the last. Also, I cannot use lastname.substr(-2) because substr for some reason won't work (not sure why, this would be much easier).
Thanks for any help.
*EDIT: I hope I didn't confuse anyone, I need the last two characters of the last name.
Actually I see my problem now: my original last name variable is
String lastname = console.nextLine().substring(0,2).trim().toUpperCase();
which keeps the first two letters, so the reason I was getting the first two letters was because of this. I understand now. Is there a way to get the last two letters from this same variable?
So if the name was Michael, you just want Micha?
Try:
String trimmedLastName = lastName.substring(0, lastName.length() - 2);
For example:
String lastName = "Michael";
String trimmedLastName = lastName.substring(0, lastName.length() - 2);
System.out.println(trimmedLastName); // prints Micha
The reason mine works and yours doesn't is because the first parameter of substring is where to start. So I start from the first letter, and end on the second last letter (not inclusive).
What yours does is start on the second last letter, and continue on until the end of the string.
However, if you wanted just el from Michael, you could do this:
String lastName = "Michael";
String trimmedLastName = lastName.substring(lastName.length() - 2);
System.out.println(trimmedLastName); // prints el
Try this out,
lastname.substring(lastname.length() -3,lastname.length() -1);
If you need the different ways, here:
StringBuffer myString = new StringBuffer(inputString);
myString.revert();
StringBuffer userInput = new StringBuffer(myString.subString(2));
String result = userInput.revert();
Have a nice day.
Because String is immutable so when you call subString it doesn't change the value of lastname.
I think you should do:
String genName = lastname.subString(lastname.lengh()-2);
lastname.substring(lastname.length() - 2) should return the last 2 letters.
lastname.substring(0, 2) returns the first two.
substring(index) is includive
substring(index1, index2) is inclusive, exclusive respectively.

Regex to parse multiline data

I have a following data from a file and I would like to see if I can do a regex parsing here
Name (First Name) City Zip
John (retired) 10007
Mark Baltimore 21268
....
....
Avg Salary
70000 100%
Its not a big file and the entire data from the file is available in a String object with a new line characters (\n) (String data = "data from the file")
I am trying to get name, city, zip and then the salary, percentage details
data inside () considered part of Name field.
For Name field space is considered valid and there are no space for other fields.
'Avg Salary' is available only at the end of the file
Will it be easy to do this via regex parsing in Java?
If the text file is space-aligned, you can (and probably should) extract the fields based on the number of characters. So, you take the first n characters in each line as first name, the next m characters as City, and so on.
This is one code to extract using the above method, by calculating the field length of the fields automatically, assuming we know the header.
String data = "data from the file";
// This is just to ensure we have enough space in the array
int numNewLines = data.length()-data.replace("\n","").length();
String[][] result = new String[numNewLines][3];
String[] lines = data.split("\n");
int avgSalary = 0;
int secondFieldStart = lines[0].indexOf("City");
int thirdFieldStart = lines[0].indexOf("Zip");
for(int i=1; i<lines.length; i++){
String line = lines[i].trim();
if(line.equals("Avg Salary")){
avgSalary = Integer.parseInt(lines[i+1].substring(0,secondFieldStart).trim());
break;
}
result[i-1][0] = line.substring(0,secondFieldStart).trim(); // First Name
result[i-1][1] = line.substring(secondFieldStart,thirdFieldStart).trim(); // City
result[i-1][2] = line.substring(thirdFieldStart).trim(); // Zip
}
Using regex will be possible, but it will be more complicated. And regex won't be able to differentiate person's name and city's name anyway:
Consider this case:
John Long-name Joe New York 21003
How would you know the name is John Long-name Joe instead of John Long-name Joe New if you don't know that the length of the first field is at most 20 characters? (note that length of John Long-name Joe is 19 characters, leaving one space between it and New in New York)
Of course if your fields are separated by other characters (like tab character \t), you can split each line based on that. And it's easy to modify the code above to accommodate that =)
Since the solution I proposed above is simpler, I guess you might want to try it instead =)

How to use String.format() in Java to replicate tab "\t"?

I'm printing data line by line and want it to be organized like a table.
I initially used firstName + ", " + lastName + "\t" + phoneNumber.
But for some of the larger names, the phone number gets pushed out of alignment
I'm trying to use String.format() to achieve this effect. Can anyone tell me the format syntax to use?
I tried String.format("%s, %s, %20s", firstName, lastName, phoneNumber), but that's not what I want. I want it to look like this:
John, Smith 123456789
Bob, Madison 123456789
Charles, Richards 123456789
Edit:
These answers seem to work for System.out.println(). But I need it to work for a JTextArea. I'm using textArea.setText()
Worked it out. JTextArea doesn't use monospaced fonts by default. I used setFont() to change that, and now it works like a charm. Thank you all for the solutions.
consider using a negative number for your length specifier: %-20s. For example:
public static void main(String[] args) {
String[] firstNames = {"Pete", "Jon", "Fred"};
String[] lastNames = {"Klein", "Jones", "Flinstone"};
String phoneNumber = "555-123-4567";
for (int i = 0; i < firstNames.length; i++) {
String foo = String.format("%-20s %s", lastNames[i] + ", " +
firstNames[i], phoneNumber);
System.out.println(foo);
}
}
returns
Klein, Pete 555-123-4567
Jones, Jon 555-123-4567
Flinstone, Fred 555-123-4567
Try putting the width into second placeholder with - sign for right padding as:
String.format("%s, %-20s %s", firstName, lastName, phoneNumber)
This will give the specified width to the second argument(last name) with right padding and phone number will start after the specified width string only.
EDIT: Demo:
String firstName = "John";
String lastName = "Smith";
String phoneNumber = "1234456677";
System.out.println(String.format("%s, %-20s %s",firstName, lastName, phoneNumber));
prints:
John, Smith 1234456677
The only alternative is loop the names list, calculate the maximum length of the String, and add whitespaces as needed after every name to ensure that all the numbers begin at the same column.
Using tabs has the disavantage that you cannot know a priori how many whitespace are equivalent to a tab, since it is dependent of the editor.

Categories