我是一个初学者,我正在尝试用java做一个简单的计算器。一切正常,除了Addition输出错误(例如1 + 1 = 1.01.0)。这是我的代码示例
package Package;
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter Equation:");
double num1 = input.nextDouble();
String oper = input.next();
String plus, minus, divide, modulus, multiply;
plus = "+";
minus = "-";
divide = "/";
multiply = "*";
modulus = "%";
//Everything is the same but addition seems to have wrong output
if (oper.equals(plus))
{
double num2 = input.nextDouble();
System.out.println("= " + num1 + num2);
}
else if (oper.equals(minus))
{
double num2 = input.nextDouble();
System.out.println(num1 - num2);
答案 0 :(得分:1)
您正在打印字符串num1
和num2
,而不是计算结果。
当您打印出一个字符串(在您的情况下为"="
时,Java会将添加到它的任何数字也视为字符串)。
要解决此问题,只需将您的计算添加到括号中,以使Java可以分别计算它们:
System.out.println("=" + (num1 + num2));