You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中System.out.print输出带加号的求和语句报错如何解决

问题原因

你写的打印语句存在两个问题,导致无法输出预期格式:

  • 拼接逻辑里没有手动添加" + "、" = "这类固定符号字符串,自然无法展示对应的连接符和等号
  • Java中+运算符是从左到右按顺序执行的,只要运算任意一侧是字符串类型,就会执行字符串拼接而非数值计算,你当前的写法只会把所有数字直接连在开头字符串后面,输出类似The sum of the digits is: 3045820的错误内容;另外你开头字符串里is后面多写了一个冒号,和目标格式不匹配。
修复方法

你只需要把需要展示的固定符号按顺序插到拼接参数中即可,如果你已经提前计算好sum变量的值,直接使用下面的写法:

System.out.print("The sum of the digits is " + num1 + " + " + num2 + " + " + num3 + " + " + num4 + " + " + num5 + " = " + sum);

如果你没有提前定义sum变量,想直接在打印语句里计算总和,一定要给数值求和部分加小括号提升运算优先级,否则会被识别为字符串拼接出错,写法如下:

System.out.print("The sum of the digits is " + num1 + " + " + num2 + " + " + num3 + " + " + num4 + " + " + num5 + " = " + (num1 + num2 + num3 + num4 + num5));

当num1=3、num2=0、num3=4、num4=5、num5=8、sum=20时,上述代码运行后就会输出你需要的结果:

The sum of the digits is 3 + 0 + 4 + 5 + 8 = 20

内容的提问来源于stack exchange,提问作者garro12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 06:06:27