Java程序PrintWriter输出异常:加法结果写入文件错误求助
问题原因分析与解决办法
嘿,这个问题我一眼就看出来啦——你的switch语句里忘记加break关键字了!
问题根源
Java的switch语句在匹配到对应的case后,会默认继续执行后续所有case的代码,直到遇到break或者switch代码块结束。你输入option=1时,程序会依次执行:
- case 1:写入
12+4=16的字符串形式 - 因为没有break,继续执行case 2:写入
12-4=8的字符串形式 - 继续执行case 3:写入
12*4=48的字符串形式 - 最后执行case 4:写入
12/4=3.0的字符串形式
这些字符串会被PrintWriter连续写入文件,最终拼接成168483.0,这就是你看到的异常结果。
修正后的代码
只需要给每个case分支加上break,让程序在执行完对应分支后跳出switch即可:
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class Test { public static void main(String[] args) throws FileNotFoundException{ int option = 0; int a; int b; System.out.println("Input the type of the calculation:"); Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(new File("C:\\Users\\123\\Desktop\\result.txt")); option = in.nextInt(); System.out.println("Input the two values:"); System.out.print("a:"); a = in.nextInt(); System.out.print("b:"); b = in.nextInt(); in.close(); // the Calculation: switch(option) { case 1: String addResult = Integer.toString(a+b); out.write(addResult); System.out.println(addResult); break; // 执行完加法后跳出switch case 2: String subResult = Integer.toString(a - b); out.write(subResult); System.out.println(subResult); break; case 3: String mulResult = Integer.toString(a * b); out.write(mulResult); System.out.println(mulResult); break; case 4: String divResult = Double.toString(1.0 * a / b); out.write(divResult); System.out.println(divResult); break; default: // 处理非法选项的默认分支 System.out.println("Invalid option!"); out.write("Invalid option!"); break; } out.flush(); out.close(); } }
额外小提示
- 养成在switch的每个case分支末尾加
break的习惯,除非你确实需要利用switch的“贯穿”特性(这种场景很少见)。 - 加上
default分支可以处理用户输入非法选项的情况,让程序更健壮。
内容的提问来源于stack exchange,提问作者Zhihao ZHAO
相关产品推荐
相关产品推荐

