gpt4 book ai didi

java - 使用 PrintWriter 打印字符串

转载 作者:行者123 更新时间:2023-12-01 23:12:16 24 4
gpt4 key购买 nike

尝试使用 PrintWriter 打印时遇到问题。

问题描述:

I am expecting to print the Press options first then take the user input but using out.println i can't do that. It's not printing the options while i run the program. It just waits for an input while i give the input it then prints the Press options.

注意: 如果我使用 System.out.println 那么它会按预期工作。

尝试如下

public class Calculator {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
StringTokenizer took = new StringTokenizer(" ");
String operator;
// System.out.println("Press '+' for Additon");
// System.out.println("Press '-' for Subtraction");
// System.out.println("Press '*' for multiplication");
out.println("Press '+' for Additon");
out.println("Press '-' for Subtraction");
out.println("Press '*' for multiplication");
out.println("Press '/' for Division");

operator=in.readLine();
switch (operator) {
case "+":
out.println("Add");
break;
case "-":
out.println("Subtract");
break;
case "*":
out.println("Multiply");;
break;
case "/":
out.println("Division");
break;
}
in.close();
out.close();
}
}

输入:

*

输出:

Press '+' for Additon
Press '-' for Subtraction
Press '*' for multiplication
Press '/' for Division

Multiply

最佳答案

做:

out.flush();

在读入之前,然后在关闭输出之前。

或者你可以这样做:

PrintWriter out =  new PrintWriter(new OutputStreamWriter(System.out), true);

true 的作用是将其设置为每次打印时自动刷新。

建议查看 PrintWriter 的 Javadoc .

关于java - 使用 PrintWriter 打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21720525/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com