Home > Software design >  Is it possible to save the iteration of for loops into a single string variable?
Is it possible to save the iteration of for loops into a single string variable?

Time:03-17

System.out.println("LEFT SIDE:");
        for (int i = 0; i < leftSide; i  )
        {
            System.out.println(this.leftStrings[i]   " "   this.leftInts[i]);
        }
System.out.println("RIGHT SIDE:");
        for (int i = 0; i < this.rightSide; i  )
        {
            System.out.println(this.rightStrings[i]   " "   this.rightInts[i]);
        }

Is there a way I can output this block of code in another class, making it a parameter or using a toString method?

CodePudding user response:

One way is to use an intermediary object as storage and print when ever wanted.

Eg: List<String>

List<String> list=new ArrayList<String>();
list.add("LEFT SIDE:");
for (int i = 0; i < leftSide; i  )
{
    list.add(this.leftStrings[i]   " "   this.leftInts[i]);
}
list.add("RIGHT SIDE:");
for (int i = 0; i < this.rightSide; i  )
{
    list.add(this.rightStrings[i]   " "   this.rightInts[i]);
}
list.forEach(System.out::println);

CodePudding user response:

As already mentioned, you can use StringBuilder to carry out the task, for example:

String ls = System.lineSeparator(); // Utilize platform specific newline character(s).
System.out.println("LEFT SIDE:");
StringBuilder sb = new StringBuilder(""); // create a StringBuilder object
// Add iterated contents to StringBuilder object
for (int i = 0; i < leftSide; i  ) {
    sb.append(this.leftStrings[i]).append(" ").append(this.leftInts[i]).append(ls);
}
// Store StringBuilder contents into a String variable
String lSide = sb.toString();
System.out.println(lSide);  // Print the lSide variable contents to console.
    
sb.setLength(0);  // Empty the StringBuilder object to prepare for a new build
System.out.println("RIGHT SIDE:");
// Add iterated contents to StringBuilder object
for (int i = 0; i < this.rightSide; i  ) {
    sb.append(this.rightStrings[i]).append(" ").append(this.rightInts[i]).append(ls);
}
// Store StringBuilder contents into a String variable
String rSide = sb.toString();
System.out.println(rSide);  // Print the rSide variable contents to console. 
  •  Tags:  
  • java
  • Related