0

I'm trying to create a toString method that would return a string representation of my object "Individual". Individual is an array of integers. The string should contain an introduction to my permutation, and both the indexes and elements of the array.

So ideally the string should look like this

  public String toString() {
    System.out.println ("The permutation of this Individual is the following: ");
    for (int i=0; i<size; i++){
      System.out.print (" " + i);
    }
    System.out.println();
    for (int i=0; i<size; i++) {
      System.out.print (" " + individual[i]);
    }
    System.out.println ("Where the top row indicates column of queen, and bottom indicates row of queen");
  }

I'm stuck on how to store and format this particular representation as a String, especially on how to store the array elements into the string.

3
  • 1
    What is individual? Show the code. Commented Feb 8, 2015 at 17:55
  • 2
    Could you include example of input and expected output? Commented Feb 8, 2015 at 17:57
  • So you need a string of indexes and and a string of int values below it and the problem is to align them? Commented Feb 8, 2015 at 17:58

2 Answers 2

3

You need a StringBuilder instead of printing it out

 public String toString() {
    StringBuilder builder =new StringBuilder();
    builder.append("The permutation of this Individual is the following: ");
    builder.append("\n");//This to end a line
    for (int i=0; i<size; i++){
       builder.append(" " + i);
    }
    builder.append("\n");
    for (int i=0; i<size; i++) {
       builder.append(" " + individual[i]);
    }
    builder.append("\n");
    builder.append("Where the top row indicates column of queen, and bottom indicates row of queen");
    builder.append("\n");
    return builder.toString();
  }
Sign up to request clarification or add additional context in comments.

1 Comment

Generally we let user decide if he wants to print some value with line separator after it or not. In other words result of toString shouldn't add \n at end of its result, so consider removing builder.append("\n"); placed right before return statement.
0

You can store array elements into string like this if you meant this:

String data = ""; // empty
ArrayList items; // array of stuff you want to store into a string

for(int i =0; i< items.size(); i++){
  data+=""+items.get(i) + ","; // appends into a string
} 

// finally return the string, you can put this in a function
return data;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.