I am doing a hangman project.
I have got most of the code working.
The one part I can't get working is where the "secret word" has more than one letter which is the same. For example "hello" has 2 "l"'s.
This is the code for the part of the code where it replaces the "----" (hello) with the letter that was guessed if the guess was right:
int pos = $Input.indexOf($Guessed);
if (pos == -1)
{
System.out.print("Search string '" + $Guessed + "' not found");
}
else
{
System.out.println("\nSearch string found at " + (pos + 1));
pos = $Input.indexOf($Guessed);
String before = $Display.substring(0, pos);
String after = $Display.substring(pos + $Guessed.length());
System.out.println(before + $Guessed + after);
$Display = before + $Guessed + after;
System.out.println($Display);
$GuessAmt++;
}
I have looked at various answers on here but I cannot get one to work so far.
Obviously if someone guessed "l" then "-----" would change to "--ll-" for (hello).
I am not looking for someone to code this for me as I enjoy a challenge but a bit of a hint would be lovely!!
Obviously from looking at my code you may be able to guess we are not allowed to use arrays yet unfortunately. This is only an intro to Java class really.
Any help would be appreciated.
EDIT: Just to be clear, at the moment it ONLY does the first "l" not both the "l"'s of (hello).
EDIT: Changed to this. However, now it is repeating the "inside if" print statement over and over. Cant see how to fix this!
int pos = $Input.indexOf($Guessed);
if (pos == -1)
{
System.out.print("Search string '" + $Guessed + "' not found");
}
else
{
//System.out.println("\nSearch string found at " + (pos + 1));
for(int i=0;i<$StrLength;i++)
{
System.out.println(i);
if($Input.charAt(i) == $Guessed.charAt(0))
{
i = $Input.indexOf($Guessed);
String before = $Display.substring(0, i);
String after = $Display.substring(i + 1);
System.out.println("inside if" + before + $Guessed + after);
$Display = before + $Guessed + after;
}
}
System.out.println($Display);
$GuessAmt++;
}
If you still wanna use the indexOf you can use its overloaded version as well to insure that you have gone through all letter occurrences:
int index = str.indexOf('l');
while(index >= 0) {
// FILL THE BLANKS WITH THE LETTER
index = str.indexOf('l', index +1);
}
You can iterate over the String and check every character individually using word.charAt(i).
for (int i = 0; i < word.length; i++) {
if (word.charAt(i) == guessedChar) {
// do stuff
}
}
Related
so I'm having a small problem in java. I have something like
"Victor Fleming"
"Gone With"
"With The"
"The Wind."
So what the sentence should actually look like is
"Victor Fleming"
"Gone with the wind."
Therefore I'm looking to form a single sentence, by words that are adjacent and the same. If no adjacent same word is detected then the sentence will be separated as in "Victor Fleming" case where Fleming is not the same with Gone, so a new sentence is starting. What I've written so far:
List<String> separatedText = new ArrayList<>();
int i = 0;
while (i < mergedTextByHeightColor.size()) {
if ((i < (mergedTextByHeightColor.size() - 3)) && !(mergedTextByHeightColor.get(i + 1).equals(mergedTextByHeightColor.get(i + 2)))) {
separatedText.add(mergedTextByHeightColor.get(i) + " " + mergedTextByHeightColor.get(i + 1));
i = i + 2;
}
String concatStr = "";
while ((i < (mergedTextByHeightColor.size() - 3)) && (mergedTextByHeightColor.get(i + 1).equals(mergedTextByHeightColor.get(i + 2)))) {
if (concatStr.contains(mergedTextByHeightColor.get(i))) {
concatStr = mergedTextByHeightColor.get(i + 1) + " " + mergedTextByHeightColor.get(i + 3);
} else {
concatStr = mergedTextByHeightColor.get(i) + " " + mergedTextByHeightColor.get(i + 1) + " " + mergedTextByHeightColor.get(i + 3);
}
i = i + 3;
}
separatedText.add(concatStr);
}
We can store the sentences in a String array, then loop through each one.
Inside the loop, we check whether the last word of the last item (by splitting it into an array with .split(" "), then getting the last element) is equal to the first word of the current item. If it is, we first remove the first word of the current item, then append it to a StringBuilder.
If it isn't, then we append the StringBuilder's value to the list, append the current element, and move on.
String[] sentences = {"Victor Fleming", "Gone With", "With The", "The Wind."};
List<String> newsentences = new ArrayList<>();
StringBuilder str = new StringBuilder();
for(int i = 0; i < sentences.length; i++) {
String cur = sentences[i];
if(i != 0) {
String[] a = sentences[i-1].split(" ");
String[] b = cur.split(" ");
String last = a[a.length-1];
String first = b[0];
if(last.equalsIgnoreCase(first)) {
str.append(cur.substring(first.length()));
}else {
newsentences.add(str.toString());
str = new StringBuilder();
str.append(cur);
}
}else {
str.append(cur);
}
}
newsentences.add(str.toString());
System.out.println(Arrays.toString(newsentences.toArray()));
Output:
[Victor Fleming, Gone With The Wind.]
I m writing a function to format a string input. The function is to make the text output left indented, with a limit to the number of characters in a line.
if there are excess whitespaces,' ', between words; i skip the excess whitespace and only put one whitespace' '. if the word is too long and will go over the character per line limit, i insert whitespaces until the limit and start a new line with that word in the newline.
i am unable to create the padding section of the code. which is the part which checks whether the word will go over the limit and to start a newline with the word in the newline.
as part of the assignment requirements, i am only allowed to use charAt() and length methods on a String
void runApp(){
String text = " Knowing You Jesus " +
" Graham Kendrick " +
"All I once held dear, built my life upon " +
"All this world reveres, and wars to own " +
"All I once thought gain I have counted loss " +
"Spent and worthless now, compared to this " +
"Knowing you, Jesus " +
"Knowing you, there is no greater thing " +
"You're my all, you're the best " +
"You're my joy, my righteousness " +
"And I love you, Lord " +
"Now my heart's desire is to know you more " +
"To be found in you and known as yours " +
"To possess by faith what I could not earn " +
"All-surpassing gift of righteousness " +
"Oh, to know the power of your risen life " +
"And to know You in Your sufferings " +
"To become like you in your death, my Lord " +
"So with you to live and never die " +
"Source: Musixmatch " +
"Songwriters: Tim Hughes / Ben Cantelon ";
//limit = 60
System.out.println(" `123456789012345678901234567890123456789012345678901234567890");`
System.out.println(leftTextFormat(text, 60));
System.out.println();
}
// This prints out everything left indented, but does not pad.
String leftTextFormat(String text, int limit){
String formattedText = "";
int charCount = 0;
formattedText = formattedText+"[";
for (int i=0; i<text.length(); i++){
if (charCount%limit ==0){
if (text.charAt(i) == ' '){
continue;
}else if (text.charAt(i) != ' ' ){
formattedText = formattedText+text.charAt(i);
charCount++;
}
}else if (charCount%limit != 0){
if (text.charAt(i) == ' '){
if (text.charAt(i-1) != ' '){
formattedText = formattedText+text.charAt(i);
charCount++;
}else{
continue;
}
}else if (text.charAt(i) != ' '){
formattedText = formattedText+text.charAt(i);
charCount++;
}
}
if (charCount%limit ==0 && charCount!=0){
formattedText = formattedText+"]\n[";
}
}
return formattedText;
}
The expected output is this:
https://drive.google.com/file/d/1uYXtSBo37sFnpwJeBGtjF0MFYNngtZXv/view?usp=sharing
what i managed to do is this:
https://drive.google.com/file/d/102zNMe4JhaO2IUoOPCS5GSZ02Pq9aXwX/view?usp=sharing
123456789012345678901234567890123456789012345678901234567890
[Knowing You Jesus Graham Kendrick All I once held dear, buil]
[t my life upon All this world reveres, and wars to own All I]
[once thought gain I have counted loss Spent and worthless no]
[w, compared to this Knowing you, Jesus Knowing you, there is]
[no greater thing You're my all, you're the best You're my jo]
[y, my righteousness And I love you, Lord Now my heart's desi]
[re is to know you more To be found in you and known as yours]
[To possess by faith what I could not earn All-surpassing gif]
[t of righteousness Oh, to know the power of your risen life ]
[And to know You in Your sufferings To become like you in you]
[r death, my Lord So with you to live and never die Source: M]
[usixmatch Songwriters: Tim Hughes / Ben Cantelon
Ok attempt, but your problem is that you only adding characters and never actually establishing if those characters make up words and if those words, which you are adding, are going to go over your "limit". Hence you have no idea when a word will actually cause you to go over your imposed limit and subsequently you are make no attempt to pad your line when you are potentially going to go over that limit.
Essentially you need to work word for word and line by line. Each time you've established a word, check that the length of that word plus the length of your current line is not greater than your limit. If it's greater don't concatenate it to your current line, rather pad the line to your limit and start a new line.
public String formattedLine(String singleLine, int limit) {
int padding = limit - singleLine.length();
String pad ="";
for(int j = 0; j < padding; j ++) {
pad += " ";
}
return "[" + singleLine + pad + "]\n";
}
public String leftTextFormat(String text, int limit) {
String word = "";
String singleLine = "";
String formattedText = "";
for(int i=0; i<text.length(); i++) {
if (text.charAt(i) != ' ') {
word = word + text.charAt(i);
} else {
if(word.length() > 0) {
if(singleLine.length() + word.length() >= limit) {
formattedText = formattedText + formattedLine(singleLine, limit);
singleLine = "";
}
if(singleLine.length() == 0) {
singleLine = word;
} else {
singleLine = singleLine + " " + word;
}
word = "";
}
}
}
formattedText = formattedText + formattedLine(singleLine, limit);
return formattedText;
}
I am currently writing . a test to compare leaderboards entries in a betting table, Firstly i have to compare the result picks or the player (which is working) and then i have to compare each players points (which is working) but if both of these attributes are the same i have to assert the player higher on the table is higher alphabetically. I have created the variables username_player and previous_user to do this but cant figure out how to do it, Im trying to put it in the else if section (which i think is correct). There doesn't seem to be an assert option to do this?
public void test_player_leaderboard_entry() {
int size = playerRows.size();
Integer previous_total = 0;
Integer previous_points = 0;
String previous_user = null;
for (int i = 0; i < size; i++) {
//Position
String position_first_player = Drivers.getDriver().findElement(By.cssSelector("[data-qa-position-value='" + i + "']")).getText();
//Points
String points_player = Drivers.getDriver().findElement(By.cssSelector("[data-qa-points-value='" + i + "']")).getText();
//Username
String username_player = Drivers.getDriver().findElement(By.cssSelector("[data-qa-player-value='" + i + "']")).getText();
//Row Number
Integer row = i + 1;
Integer point_player = Integer.parseInt(points_player);
Integer total_of_won_and_looking_good = 0;
//PICKS
for (int pick_number = 1; pick_number < 5; pick_number++) {
String pick_status = Drivers.getDriver().findElement(By.xpath("//*[#id='root']/div/main/section[2]/section/div/ol/a[" + row + "]/li/div[3]/div[" + pick_number + "]/div")).getAttribute("data-qa-pick-state");
//System.out.println(pick_status);
if (Integer.parseInt(pick_status) == 2 || Integer.parseInt(pick_status) == 1) {
total_of_won_and_looking_good = total_of_won_and_looking_good + 1;
}
} if(previous_total.equals(total_of_won_and_looking_good)) {
Assert.assertTrue(previous_points > point_player);
System.out.println("Picks are the same, points are higher ");
} else if (previous_total.equals(total_of_won_and_looking_good)&& previous_points.equals(point_player)) {
Assert.assertTrue(previous_user.compareTo(username_player) < 0);
}
previous_total = total_of_won_and_looking_good;
previous_points = point_player;
previous_user = username_player;
System.out.println("On row number " + row + " we find " + username_player + " in position " + position_first_player + " with " + total_of_won_and_looking_good + " correct picks and " + points_player + " points!");
}
}
}
You can use the compareTo method.
Try using an assertion for previous_user.compareTo(username_player) <0
You can use compareTo method on Strings which compares them lexicographically. So you can do something like
Assert.assertTrue(previous_user.compareTo(username_player) < 0)
Edit:
Maybe you can try it like this but I am not entirely sure that is what you want:
if(previous_total.equals(total_of_won_and_looking_good)) {
Assert.assertTrue(previous_points > point_player);
System.out.println("Picks are the same, points are higher ");
} else if (previous_points.equals(point_player)) {
Assert.assertTrue(previous_user.compareTo(username_player) < 0);
}
String site_inclusion = "0;100";
for (String inc: site_inclusion.split(";")) {
if(!inc.equals(String.valueOf(record.getAttrs().get(new PdsxAttrKey("SiteId")).getValue()))) {
continue;
}
}
And record.getAttrs().get(new PdsxAttrKey("SiteId")).getValue() returns 77
So from my code it should be going to continue block right? But it is not going to continue?
Any suggestions?
I suggest you simplify your code to test what's going on. You might have made a mistake trying to build an example.
String site_inclusion = "0;100";
for (String inc: site_inclusion.split(";")) {
String temp = String.valueOf(record.getAttrs().get(new PdsxAttrKey("SiteId")).getValue());
if(!inc.equals(temp)) {
System.out.println(inc + " != " + temp);
continue;
}
System.out.println(inc + " == " + temp);
}
It would be better for you to check what are the variables (System.out.println/debugging).
The reason why it's not going in that way you think is for sure that condition in if statement.
Try splitting your code into smaller pieces.
String site_inclusion = "0;100";
for(String inc : site_inclusion.split(";")) {
int value = record.getAttrs().get(new PdsxAttrKey("SiteId")).getValue();
System.out.println("Inc = " + inc + " and value = " + value);
if(!inc.equals(String.valueOf(value))) {
System.out.println("continue");
continue;
}
System.out.println(inc + " equals " + value);
}
I need to automate search functionality as below:
Search string = (X* OR "Y") AND Z
On entering this search system should assert the result. My problems are:
1) How to make precedence among operators because if there is () then that should be executed and with its result other parts of search string to be checked.
2) termi* can be terminate, terminator. How do we check this and assert
3) "Stack Overflow" means the result should have exactly matched. How can we find and assert
4) Likewise NOT operator, how can we assert
Pls share with me if any kind of help you can provide.
Thanks in advance.
Some how managed to write code in java using StringBuffer :)
Instead of storing the result of first block and process next I have created a string command based on the searchString as below and finally fire the newly created command and verified the answer.
Like whenevenever AND comes in searchString we insert && operator and for OR || operator.
String[] arrSearch=searchString.split("\\s");
StringBuffer sb = new StringBuffer();
boolean skipFlag = false;
for(int i=0;i<arrSearch.length;i++){
System.out.println(arrSearch[i]);
if(!skipFlag && arrSearch[i].startsWith("\"")){
skipFlag = true;
continue;
}else if(skipFlag){
if(arrSearch[i].endsWith("\"")){
skipFlag = false;
continue;
}else{
continue;
}
}else if(arrSearch[i].startsWith("(")){
String temp = arrSearch[i].substring(1);
sb.append("(selenium.isTextPresent(" + temp + ")" + " ");
}else if(arrSearch[i].startsWith(")")){
String temp = arrSearch[i].substring(0,arrSearch[i].length()-1);
sb.append("selenium.isTextPresent(" + temp + "))" + " ");
}else if(arrSearch[i].equalsIgnoreCase("AND")){
sb.append("&&" + " ");
}else if(arrSearch[i].equalsIgnoreCase("OR")){
sb.append("||" + " ");
}else if(arrSearch[i].equalsIgnoreCase("NOT")){
sb.append("!");
}else if(arrSearch[i].endsWith("*")){
String temp = arrSearch[i].substring(0,arrSearch[i].length()-1);
sb.append("selenium.isTextPresent(\"//*[contains('" + temp + "')]\")" + " ");
}else{
sb.append("selenium.isTextPresent(" + arrSearch[i] + ")" + " ");
}