如何将字符串插入输出字符串流
How to insert string into the output string stream
我只想编写将我的 userItems 插入输出字符串流 itemsOSS 的代码。我的每个项目后面都会跟着一个 space。我希望输出反映以下内容,例如 "red purple yellow Exit":
输出示例,
红紫黄
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;
}
}
我找到了有效的代码,我只需要使用打印方法。
itemsOSS.print(userItem + " ");
userItem = itemCharStream.toString();
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);
}
}
这个有效
我只想编写将我的 userItems 插入输出字符串流 itemsOSS 的代码。我的每个项目后面都会跟着一个 space。我希望输出反映以下内容,例如 "red purple yellow Exit":
输出示例,
红紫黄
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;
}
}
我找到了有效的代码,我只需要使用打印方法。
itemsOSS.print(userItem + " ");
userItem = itemCharStream.toString();
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);
}
}
这个有效