Search code examples
javastringstreamprintwriter

How to insert string into the output string stream


I want to simply write code that inserts my userItems into the output string stream itemsOSS. Each of my item will be followed by a space. I want the output to reflect the following for example, "red purple yellow Exit":

Output example,

red purple yellow

public class StringStreamOutput {

   public static void main (String [] args) {

      Scanner scnr = new Scanner(System.in);
      String userItem = "";

      StringWriter itemCharStream = new StringWriter();
      PrintWriter itemsOSS = new PrintWriter(itemCharStream);

      System.out.println("Enter items (type Exit to quit):");
      userItem = scnr.next();

      while (!userItem.equals("Exit")) {

         // confused here, 

         userItem = scnr.next();
      }

      userItem = itemCharStream.toString();
      System.out.println(userItem);

      return;
   }
}

Solution

  • I found the code that works, I just needed to utilize the print method.

    itemsOSS.print(userItem + " "); 
    
    userItem = itemCharStream.toString();