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

Java项目报错:运算符-对String、double类型参数未定义

The operator - is undefined for the argument type(s) String, double - Fix Explained

Hey there, let's break down this error you're facing and fix it right away.

What's Causing the Error?

Your problematic code line is:

System.out.println("the result is: \n" + num1 - num2);

The root issue is Java's operator precedence rules. Operators like + (string concatenation) and - (subtraction) have the same precedence, so Java evaluates them from left to right.

Here's the play-by-play:

  1. First, Java runs "the result is: \n" + num1 — this turns the entire expression into a String (since you're concatenating a string with a number).
  2. Next, it tries to do [resulting String] - num2 — but Java has no built-in way to subtract a double from a String. That's exactly why you get the error message: The operator - is undefined for the argument type(s) String, double.

How to Fix It

You need to tell Java to calculate the subtraction before doing any string concatenation. Parentheses () have higher precedence than both + and -, so wrapping the arithmetic operation in parentheses will force Java to handle that part first.

Here's the corrected code:

System.out.println("the result is: \n" + (num1 - num2));

Now Java will first compute num1 - num2 (resulting in a double value), then concatenate that result to your string—no more errors!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:48:43