Can anyone figure out why after removing a found value, the output includes all the information from before the remove?
// Prints current items in both arrays
String titles = "";
String lengths = "";
for (int i = 0; i < numOfSongs; i++) {
titles += songTitles[i] + " ";
lengths += songLengths[i] + " ";
}
JOptionPane.showMessageDialog(null, "**Current Playlist**" + "\nSong titles: " + titles + "\nSong lengths: " + lengths);
// Determines if the user wants to remove a song from the current list
boolean found = false;
// If search matches a song in array, set title to null and length to 0
for (int i = 0; i < songTitles.length; i++) {
if (search.equalsIgnoreCase(songTitles[i])) {
found = true;
songTitles[i] = null;
songLengths[i] = 0;
}
}
// Update arrays, song count, and duration across all songs
if (found) {
titles += songTitles[numOfSongs] + " ";
lengths += songLengths[numOfSongs] + " ";
totalDuration -= songLengths[numOfSongs];
numOfSongs--;
}
// Print updated playlist
JOptionPane.showMessageDialog(null, "**Current Playlist**" + "\nSong titles: " + titles + "\nSong lengths: " + lengths);
titles and totalDuration strings are initialized with all the elements in songTitles and songLengths.
If you find search in songTitles you remove it from songTitles but you don't update songTitles. Instead you append on more song title from songTitles.
You probably want to clear songTitles and songLengths and recreate them skipping null values in songTitles. E.g.
titles = "";
lengths = "";
for (int i = 0; i < numOfSongs; i++) {
if (songTitles[i] != null) {
titles += songTitles[i] + " ";
lengths += songLengths[i] + " ";
}
}
Also consider creating your strings like this (Java 8)
String titles = String.join(" ", songTitles);
String lengths = String.join(" ", songLengths);
Below statements are causing to concatenate with old values.
titles += songTitles[numOfSongs] + " ";
lengths += songLengths[numOfSongs] + " ";
You should first clear the existing values by setting strings empty before adding a new value.
titles = "";
lengths = "";
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 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);
}
I hava a code similar to the code below.
I want to print all iterations' output together, not separately.
Is there anybody here to help me with it?
HashMap<String, String> myHashMap = new HashMap <String, String>();
for (int j = 0; j < x.length(); j++)
int firstElement = 0;
int secondElement = 1;
if (myArray.length() > 0) {
String first = myArray.get(firstElement).toString();
String last = myArray.get(secondElement).toString();
//System.out.println(first + " --> " + last);
boolean a = Info.contains("xxx");
boolean b = Info.contains("yyy");
if( a || b ) {
//System.out.println(first + " --> " + last);
count++;
myHashMap.put(first, last);
System.out.println(count + "\t" + first);
total = total + " " + first;
}
}
}
Here I can print the output for each iteration.
But I need to print all together. Is there any way to save them into a HashMap and print them all together?
Assuming your code works correctly, this is one of the possible ways:
StringBuilder sb = new StringBuilder(); // Defined outside of the for loop
...
if( a || b ) {
//System.out.println(first + " --> " + last);
count++;
myHashMap.put(first, last);
System.out.println(count + "\t" + first);
total = total + " " + first;
sb.append(count).append("\t").append(first).append("\n");
}
...
System.out.println(sb.toString()); // Print out the output after the for loop.
public String foodstats (){
String foodstats = "";
for ( int i = 0; i < consumables.size(); i++){
foodstats = "Name: " + consumables.get(i).getName() + "\tNutrition: " + consumables.get(i).getNValue() + "\tStamina: " + consumables.get(i).getStamina() + "\n" ;
}
return foodstats;
}
So this returns: Name: Water Nutrition: 30 Stamina : 15
I realize why its doing this, the second time the for loop runs through it replaces the first item's stats and returns only the replaced stats.
Is there a way around this? I need to return all the item's stats based on the array list size.
I think what you are looking for is a StringBuilder, more efficient in that case than += concatenation :
public String foodstats (){
StringBuilder foodstats = new StringBuilder();
for ( int i = 0; i < consumables.size(); i++){
foodstats.append("Name: " + consumables.get(i).getName() + "\tNutrition: " + consumables.get(i).getNValue() + "\tStamina: " + consumables.get(i).getStamina() + "\n");
}
return foodstats.toString();
}
Make a StringBuilder and use append(...) in the loop. Once you are done, call toString() on the result, like this:
StringBuilder res = new StringBuilder();
for ( int i = 0; i < consumables.size(); i++){
res.append("Name: " + consumables.get(i).getName() + "\tNutrition: " + consumables.get(i).getNValue() + "\tStamina: " + consumables.get(i).getStamina() + "\n");
}
return res.toString();
Note: you could use foodstats += ... syntax, too, but that would be inferior, because each iteration of the loop would create a throw-away temporary object.
public String foodstats()
{
StringBuilder foodstats = new StringBuilder();
for (int i = 0; i < consumables.size(); i++)
{
foodstats.append("Name: ");
foodstats.append(consumables.get(i).getName());
foodstats.append("\tNutrition: ");
foodstats.append(consumables.get(i).getNValue());
foodstats.append("\tStamina: ");
foodstats.append(consumables.get(i).getStamina());
foodstats.append("\n");
}
return foodstats.toString();
}
I want to search object inside arraylist get value from user input and print it to text area. here is the code.
//the arrayList I declared
Book[]myBook = new Book [30];
int index = 0;
private void searchBtnActionPerformed(java.awt.event.ActionEvent evt) {
String title = titleTF.getText();
boolean found = false;
for (int i = 0; i < index; i++) {
if (myBook[i].getTitle().equals(title));
{
outputTA.append("Book Title : " + myBook[i].getTitle() + "\n");
outputTA.append("Book Author : " + myBook[i].getAuthor() + "\n");
outputTA.append("Year of Publication : " + myBook[i].getYear() + "\n");
outputTA.append("Book Status : " + myBook[i].getStatus() + "\n");
outputTA.append("======================================\n");
found = true;
break;
}
}
if (found == false) {
JOptionPane.showMessageDialog(this, "Book is not Found! Please Try again!");
}
}
The problem is, when I click the search button, it will display the first object in the arraylist. Which line of code is wrong?
First off, your index is 0 so your for doesn't loop. Replace index with myBook.size()