如何将字符串插入输出字符串流

时间:2017-11-11 14:46:48

标签: java stringstream printwriter

我想简单地编写将userItems插入输出字符串stream items的代码。我的每个项目后面都会有一个空格。我希望输出反映以下内容,例如“红紫黄色退出”:

输出示例,

红紫黄

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

2 个答案:

答案 0 :(得分:1)

我找到了有效的代码,我只需要使用print方法。

itemsOSS.print(userItem + " "); 

userItem = itemCharStream.toString();

答案 1 :(得分:0)

import java.util.Scanner;
import java.io.PrintWriter;
import java.io.StringWriter;

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")) {

         /* Your solution goes here  */
         itemsOSS.print(userItem + " ");


         /* this does not to be added as it sits outside the loop
         userItem = itemCharStream.toString();
         */

         userItem = scnr.next();
      }

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

这有效