Below is my toString() method in which I am trying to invoke another toString() from a different class called Tree. I am trying to return each part of an ArrayList and format it into my toString() from my Tree class, then put it all into the "result" String.
So far, all my method does is go through the list and return nothing. How do I make it so it essentially puts the entire list into the result string, under the format of my toString() from my Tree class?
public String toString(){
String result;
int i = 0;
while(i < listOfTrees.size()){
listOfTrees.get(i);
i++;
}
Use a StringBuilder :
public String toString(){
StringBuilder result = new StringBuilder();
int i = 0;
while(i < listOfTrees.size()){
result.append(listOfTrees.get(i) + " "); // this would use the toString
// method of the type contained
// in this List
i++;
}
return result.toString();
}
You need to use a StringBuilder. Get each String append it to the builder and then return the final String produced by it
public String toString(){
StringBuilder str= new StringBuilder();
for(int i = 0; i < listOfTrees.size(); i++){
str.append(listOfTrees.get(i));
}
return str.toString();
}
The other way to do it is to initialize result with an empty String literal to start with and then use the + operator to add other Strings to it, but this is awfully inefficient as Strings are immutable and each time you add a String that way, you create a whole new object.
Related
#Override
public String toString() {
int currentSpeed = getSpeed();
int currentGear = getGear();
StringBuffer sb = new StringBuffer("Transmission (speed = ");
sb = sb.append(currentSpeed).append(", gear = ").append(currentGear).append(")");
return sb.toString();
}
I'm confused how to convert the StringBuffer object I created back to a string format.
Since I'm calling toString() method to convert it back, I'm not sure if this will trigger the build in toString() method or else be a recursive call to the function itself?
I am writing a short Java script to where I have a name in String as a variable. I want to write get method to get initials and return them for later use. That method works well when printing out the initials, but not when wanting to return that value.
//method for getting initials of the name
public String getInitials() {
String words[] = competitorName.split(" ");
for(String word : words) {
return word.charAt(0) + " ";
}
}
It shows me that the method must return a result of type String but that should already be it. And does not work even when I am adding toString methods (then it writes that it is already String)
You almost got it! Just use StringBuilder and return result
public String getInitials() {
String words[] = competitorName.split(" ");
StringBuilder builder = new StringBuilder();
for(String word : words) {
builder.append(word.charAt(0));
}
return builder.toString();
}
I have an array of objects and each of those objects has information for a specific person, how can I iterate over each object in that array and return their information in this toString()?
#Override
public String toString()
{
String tempString = " ";
for(int i = 0; i < personArray.length; i++)
{
tempString = " All people currently residing on the stack: " +personArray[i];
}
return ""+tempString;
}
I know do not need the array to do this, but I just wanted to know how to do it using a for-loop. I will continue to work on this, but I just want to know.
You are keep ovveriding the string inside for loop . You should attached one to another. Inshort concatenate your current result with previous results.
for(int i = 0; i < personArray.length; i++)
{
tempString += " All people currently residing on the stack: " +personArray[i];
--------^
}
That way you can store the previous objects String notation and add the new result to it. In the end you can have a whole result in tempString.
The more readable and efficient way is to use a StringBuilder
#Override
public String toString()
{
StringBuilder builder = new StringBuilder();
for(int i = 0; i < personArray.length; i++)
{
builder.append(" All people currently residing on the stack: " +personArray[i]);
}
return builder.toString();
}
Note that you must have implemented the toString method of Person class already otherwise you end up seeing gibberish output in your result.
I am working with a program in which I need to use a method call to return a String from an int array. This is what I have of the method so far (I am required to use a method with this header and parameters)
public String toString()
{
for (int i=0;i<NUM_POCKETS;i++)
{
this.getPocketCount(i);
}
}
I basically need the loop to go through all of my "pockets" (array items) and return the stored values into a String to be returned.
I could be missing something very obvious, but for the life of me I do not understand how this information would be stored and returned to the Driver as a String. I know the loop logic is there, but how do I store each increment of i into a String as the loop progresses?
Thanks in advance for any help!
"I am working with a program in which I need to use a method call to return a String from an int array."
If this isn't a homework problem, you can simply use Arrays.toString(int[] array).
String myString = Arrays.toString(myIntArray);
Otherwise, maybe you can do something like this:
String getStringFromIntArray(int[] array) {
StringBuilder builder = new StringBuilder();
for (int num : array)
builder.append(num)
return builder.toString();
}
Try looking into the StringBuilder class. The specification for Java 6 is here.
http://docs.oracle.com/javase/6/docs/api/java/lang/StringBuilder.html
You would need a StringBuilder object and just append the value to the object using the .append() function.
as long as this.getPocketCount(i); gives you the value of the array on position i:
public String toString() {
String returnstring= ""; //init empty string
for (int i = 0; i < NUM_POCKETS; i++) {
returnstring += this.getPocketCount(i)+" "; //append(concat) to string
}
returnstring = returnstring.substring(0, returnstring.length()-1); //remove the last " "
return returnstring; //return string
}
the + sign appends the next string
"Hello"+" "+"World" becomes "Hello World"
Edit:
public String toString() {
String returnstring= ""; //init empty string
for (int i = 0; i < NUM_POCKETS-1; i++) { //-1 to place last later
returnstring += this.getPocketCount(i)+" "; //append to string
}
returnstring += this.getPocketCount(NUM_POCKETS-1) //append the last value
return returnstring; //return string
}
Assuming you specifically want to build your String from within the loop, you could use a StringBuilder. It is more verbose than the one-liner offered by Arrays.toString(), but you asked for it:
e.g.
public String toString() {
StringBuilder sb = new StringBuilder(NUM_POCKETS);
for (int i = 0; i < NUM_POCKETS; i++) {
sb.append(this.getPocketCount(i));
}
return sb.toString();
}
Using a StringBuilder within a loop is faster than performing concatenation of each individual element. See: when to use StringBuilder in java
Having read the documentation of Java's String class, it doesn't appear to support popping from front(which does make sense since it's basically a char array). Is there an easy way to do something like
String firstLetter = someString.popFront();
which would remove the first character from the string and return it?
A String in Java is immutable, so you can't "remove" characters from it.
You can use substring to get parts of the String.
String firstLetter = someString.substring(0, 1);
someString = someString.substring(1);
You can easily implement this by using java.lang.StringBuilder's charAt() and deleteCharAt() methods. StringBuilder also implements a toString() method.
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuilder.html
I don't think there is something like that (even because strings can't be changed - a new one needs to be created), but You can use charAt and subString to implement your own.
An example of charAt:
String aString = "is this your homework Larry?";
char aChar = aString.charAt(0);
Then subString:
String anotherString = aString.substring(1, aString.length());
So you basically want to have the String in a FIFO stack? For that you can use a LinkedList which offers under each a pop() method to pop the first from the stack.
To get all characters of a String in a LinkedList, do so:
String string = "Hello World";
LinkedList<Character> chars = new LinkedList<Character>();
for (int i = 0; i < string.length(); i++) chars.add(string.charAt(i));
Then you can pop it as follows:
char c = chars.pop();
// ...
Update: I didn't see the comment that you'd like to be able to get the remaining characters back as a string. Well, your best bet is to create and implement your own StringStack or so. Here's a kickoff example:
public class StringStack {
private String string;
private int i;
public StringStack(String string) {
this.string = string;
}
public char pop() {
if (i >= string.length()) throw new IllegalStateException("Stack is empty");
return string.charAt(i++);
}
public String toString() {
if (i >= string.length()) throw new IllegalStateException("Stack is empty");
return string.substring(i, string.length());
}
}
You can use it as follows:
String string = "Hello World";
StringStack stack = new StringStack(string);
char c = stack.pop();
String remnant = stack.toString();
// ...
To make it more solid, you can eventually compose a LinkedList.
You should look at a StringReader. The read() method returns a single character.