简体   繁体   中英

Initializing a string with elements of an int array

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.

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();
  }

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM