I want to print multiple Strings from an Array utilizing a for-loop, it will print a full first and last name, but only once. Here's my method for doing this.
This is the output I get:
"firstName secondName, "
There should be mutliple full names being printed.
The problem here is that in each iteration, you create a new memory location for list and so every time the loop executes, the value of list is overwritten. You can fix this by appending to list instead of changing the value of list in every iteration.
A side note, since Strings are immutable in java, for every iteration of the for loop, new memory will be allocated for list. This is not very efficient. You should instead use StringBuilder which is mutable. It would look like this.
StringBuilder str = new StringBuilder(list);
Then you can append to str :
str.append("any string");
This is equivalent to str + "any string"
Using StringBuilder, memory will be allocated to str only once and all the changes will take in place which is much more efficient. And finally you want to return a String object so you can call the method toString() on the StringBuilder object to convert it back into a String.
So, finally it would look like this :
public String getTANames() {
StringBuilder str = new StringBuilder("");
for(int i = 0; i < TAList.length; i++){
str.append(TAList[i].first + " " + TAList[i].second + ", ");
}
return str.toString();
}
You are very close. The problem is you keep resetting list every time you iterate over TANames. Try this instead:
public String getTANames() {
String list = "";
for(int i = 0; i < TAList.length; i++){
list += TAList[i].first + " " + TAList[i].second + ", ";
}
return list;
}
The difference is this line here: list += TAList[i].first + " " + TAList[i].second + ", "; you are adding to list not setting list.
In your current code, every loop changes the value of the list variable. To fix the issue, replace the current = with the += as follows:
list += TAList[i].first + " " + TAList[i].second + ", ";
public String getTANames() {
String list = "";
for(int i = 0; i < TAList.length; i++){
list += TAList[i].first + " " + TAList[i].second + ", ";
}
return list;
}
Hope that helps.
Related
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 = "";
Problem: I am unable to return values entered in an Array to a preview textbox
Ideal solution: User presses refresh, the box is populated with the objects in the array.
JDK: 1.8
Working Command Line Version Code:
public static void printAll(Member[] platoon){
//System.out.println("You are in the third loop");
for (int cntr=0;cntr<platoon.length;cntr++){
System.out.println("Member Name: " + platoon[cntr].getName() + " " + "Join Date: " + platoon[cntr].getJoinDate());
}
}
The above code takes a instantiated array of object type Members and returns via get methods each value stored in each Member(String Name, int day, int month, int year);.
I am attempting to do the same thing with the GUI abilities of Java. My code is somewhere around 300 lines, I am definitely willing to post it all as this is the last thing keeping me from finishing my project.
Below I write the action event that I want to use to set the text in the preview textfield with the current contents of the platoon Array. All I was attempting to do with this was place the print out from the above code into the box, it does not like the type VOID so i switched it to the return type String. Now It doesn't appear I can store the results of a For loop as a String? I am surley missing something vital.
GUI Code:
}else if(event.getSource() == refreshButton){
displayText.setText(setPreview(platoon));
}
public static String setPreview(Member[] platoon){
//System.out.println("You are in the fourth loop");
preview = (for (int cntr=0;cntr<platoon.length;cntr++){
System.out.println("Member Name: " + platoon[cntr].getName() + " " + "Join Date: " + platoon[cntr].getJoinDate()););
return preview;
}
}
Thank you all for your help, will keep this OP updated to help future Stack Overflow members with this issue.
Loops don't return results, interesting idea, Java just doesn't do.
You could...
Use a StringJoiner
StringJoiner joiner = new StringJoiner("\n");
for (int cntr=0;cntr<platoon.length;cntr++){
joiner.add("Member Name: " + platoon[cntr].getName() + " " + "Join Date: " + platoon[cntr].getJoinDate());
}
return joiner.toString();
You could...
Use JTextArea#append
for (int cntr = 0; cntr < platoon.length; cntr++) {
ta.append("Member Name: " + platoon[cntr].getName() + " " + "Join Date: " + platoon[cntr].getJoinDate() + "\n");
}
You could...
Use JList which is designed to present a list of "stuff".
See How to use lists for more details
Your problem is in your setPreview method. You using System.out.println which is an instruction to print text to the system's standard output device (in most cases a terminal window). It does not return a string, and you cannot concatenate a string to a variable using this syntax:
preview = for(...) { ... }
Since setPreview will return a single String I suspect you want to do this instead:
public static String setPreview(Member[] platoon){
String result = "";
for (int cntr=0;cntr<platoon.length;cntr++){
if (result.length() > 0) result += " "; // put a space before the next output
result += "Member Name: " + platoon[cntr].getName() + " " + "Join Date: " + platoon[cntr].getJoinDate());
}
return result;
}
This will build up the output string you need which can then be set to the text field or whatever is appropriate.
Override the toString() method in Member:
#Override
public String toString() {
return "Member Name: " + getName() + " Join Date: " + getJoinDate();
}
PrintAll() will become (but you don't need it any more):
public static void printAll(Member[] platoon) {
for (int cntr = 0; cntr < platoon.length; cntr++)
System.out.println(platoon[cntr].toString());
}
setPreview() will become (NOTE: this is only to show the principle, for better ways how to concatenate Strings in a loop see #MadProgrammer's answer):
public static String getPreviewText(Member[] platoon) {
String s = platoon.length > 0 ? platoon[0].toString() : "";
for (int i = 1; i < platoon.length; i++)
s += "\n" + platoon[i].toString();
return s;
}
public static void setPreview(Member[] platoon) {
displayText.setText(getPreviewText(platoon));
}
I have this DieRolling class that we are making for AP Computer Science. This method is supposed to return all the numbers they have rolled in a "neat" manner. Here is the code:
public void printNum()
{
for (int i=0;i<100;i++)
{
System.out.println("Roll " + (i+ 1) + ": " + numbers[i]);
}
}
I need to return the whole for loop, but I cant figure out how.
What should I do?
Thanks!
(This is my first post on here so sorry if it is kind of messed up)
You should declare printNum as a String then result a concatenate of all strings.
public String printNum(final int pToPrint)
{
StringBuilder result = new StringBuilder();
for(int i = 0; i < pToPrint; i++)
result.append("Roll " + (i+ 1) + ": " + numbers[i] + System.lineSeparator());
return result.toString();
}
Then you would call for example System.out.println(printNum(100));
You could simply return the array...
public int[] printNum() {
// ...
return numbers;
}
If you want to format the result, you could use
public String printNum() {
// ...
Arrays.toString(numbers);
}
If you want to customise the format, you could use...
public String printNum() {
StringBuilder sb = new StringBuilder(128);
for (int i=0;i<numbers.length;i++)
{
System.out.println("Roll " + (i+ 1) + ": " + numbers[i]);
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(numbers[i]);
}
return sb.toString();
}
Or if you're using Java 8
public String printNum() {
StringJoiner joiner = new StringJoiner(", ");
for (int i=0;i<numbers.length;i++)
{
System.out.println("Roll " + (i+ 1) + ": " + numbers[i]);
joiner.add(Integer.toString(numbers[i]));
}
return sb.toString();
}
You'll first need to change the return type from void to something reasonable. I suggest that you use either an array of int, since you apparently know that you'll be returning exactly 100 numbers, or an ArrayList<Integer> if that assumption is incorrect, fill up your array or List in the loop, and return it. AGain, you'll need to change the return type to be the type of whatever you decide to return.
Since this is homework, the details should be left to you.
You can return only one time from a function.
So if you want to return all numbers, you can return an array if that numbers.
Just create a String variable String result = ""; and at each loop add numbers to the string. result += "Roll " + (i+ 1) + ": " + numbers[i] + "\n";
Or something. But you for sure need to change your return type. For the above solution it should be String instead of void.
I'm trying to increment/decrement a user score as appropriate inside a text field on a (very) basic GUI. How, I only succeed in decrementing even though there is proof my conditional works correctly. Here is the pertinent code; I can supply more as needed.
//buttons: array of JButtons
//scoretxt: JTextField holding the score
//name- object name stored as string in separate string array
//check- odd numbers pass incorrect, evens pass correct
//safe: JTextArea for output
for (int i = 0; i < 18; i++) {
final String myname = "" + (buttons[i].getClientProperty("name"));
final String myval = "" + (buttons[i].getClientProperty("value"));
final String corr = "" + (buttons[i].getClientProperty("check"));
buttons[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
safe.append(myname + " " + ("" + myval));
if (corr == "correct") {
safe.append(" " + corr + "\n");
scoretxt.setText("" + ((Integer.parseInt(scoretxt.
getText())) + 1));
} else {
safe.append(" " + corr + "\n");
scoretxt.setText("" + ((Integer.parseInt(scoretxt.
getText())) - 1));
}
}
});
mygui.add(buttons[i]);
}
I have tried various approaches but I always rely on scoretxt.getText() to pass a value. Any and all help is appreciated, thanks.
You should be using the equals() method to compare two strings.
corr.equals("correct");
Please refer to How do I compare strings in Java?
I want to execute a query like
select ID from "xyz_DB"."test" where user in ('a','b')
so the corresponding code is like
String s="(";
for(String user:selUsers){
s+= " ' " + user + " ', ";
}
s+=")";
Select ID from test where userId in s;
The following code is forming the value of s as ('a','b',)
i want to remove the comma after the end of array how to do this ?
Here is one way to do this:
String s = "(";
boolean first = true;
for(String user : selUsers){
if (first) {
first = false;
} else {
s += ", ";
}
s += " ' " + user + " '";
}
s += ")";
But it is more efficient to use a StringBuilder to assemble a String if there is looping involved.
StringBuilder sb = new StringBuilder("(");
boolean first = true;
for(String user : selUsers){
if (first) {
first = false;
} else {
sb.append(", ");
}
sb.append(" ' ").append(user).append(" '");
}
sb.append(")");
String s = sb.toString();
This does the trick.
String s = "";
for(String user : selUsers)
s += ", '" + user + "'";
if (selUsers.size() > 0)
s = s.substring(2);
s = "(" + s + ")";
But, a few pointers:
When concatenating strings like this, you are advised to work with StringBuilder and append.
If this is part of an SQL-query, you probably want to sanitize the user-names. See xkcd: Exploits of a Mom for an explanation.
For fun, a variation of Stephen C's answer:
StringBuilder sb = new StringBuilder("(");
boolean first = true;
for(String user : selUsers){
if (!first || (first = false))
sb.append(", ");
sb.append('\'').append(user).append('\'');
}
sb.append(')');
you could even do the loop it like this :-)
for(String user : selUsers)
sb.append(!first || (first=false) ? ", \'" : "\'").append(user).append('\'');
Use the 'old style' of loop where you have the index, then you add the comma on every username except the last:
String[] selUsers = {"a", "b", "c"};
String s="(";
for(int i = 0; i < selUsers.length; i++){
s+= " ' " + selUsers[i] + " ' ";
if(i < selUsers.length -1){
s +=" , ";
}
}
s+=")";
But as others already mentioned, use StringBuffer when concatenating strings:
String[] selUsers = {"a", "b", "c"};
StringBuffer s = new StringBuffer("(");
for(int i = 0; i < selUsers.length; i++){
s.append(" ' " + selUsers[i] + " ' ");
if(i < selUsers.length -1){
s.append(" , ");
}
}
s.append(")");
Use StringUtils.join from apache commons.
Prior to adding the trailing ')' I'd strip off the last character of the string if it's a comma, or perhaps just replace the trailing comma with a right parenthesis - in pseudo-code, something like
if s.last == ',' then
s = s.left(s.length() - 1);
end if;
s = s + ')';
or
if s.last == ',' then
s.last = ')';
else
s = s + ')';
end if;
Share and enjoy.
i would do s+= " ,'" + user + "'"; (place the comma before the value) and add a counter to the loop where i just do s = "'" + user + "'"; if the counter is 1 (or 0, depending on where you start to count).
(N.B. - I'm not a Java guy, so the syntax may be wrong here - apologies if it is).
If selUsers is an array, why not do:
selUsers.join(',');
This should do what you want.
EDIT:
Looks like I was wrong - I figured Java had this functionality built-in. Looks like the Apache project has something that does what I meant, though. Check out this SO answer: Java: function for arrays like PHP's join()?
I fully support Stephen C's answer - that's the one I wanted to suggest aswell: simply avoid adding the additional comma.
But in your special case, the following should work too:
s = s.replace(", \\)", ")");
It simply replaces the substring ", )" with a single bracket ")".
Java 1.4+
s = s.replaceFirst("\\, \\)$", ")");
Edited: I forgot last space before parethesis
StringBuilder has a perfectly good append(int) overload.
String [] array = {"1","2","3" ...};
StringBuilder builder = new StringBuilder();
builder.append(s + "( ")
for(String i : array)
{
if(builder.length() != 0)
builder.append(",");
builder.append(i);
}
builder.append(" )")
Answer shamelessly copied from here