-3

I'm a beginner and I am trying to make a simple calculator in java. Everything works fine except for Addition has wrong output (e.g. 1+1 = 1.01.0). Here is a sample of my code

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);
NZ NORIZON
  • 11
  • 2
  • 1
    `"= " + num1` is string concatenation. If you want number addition, you need `"= " + (num1 + num2)`. VtC as trivial typo. – Andrey Tyukin Dec 29 '18 at 07:39
  • `+` is either addition or string concatenation. It is string concatenation is either side is a string, so `"= " + num1` is string concatenation, and `... + num2` is another string concatenation. Use `"= " + (num1 + num2)` to make sure numbers are added *before* being concatenated with the string. – Andreas Dec 29 '18 at 07:40
  • 2
    @AndreyTyukin - This is a mistake, not a typo. A typo is when you accidentally typed the wrong symbols. The OP deliberately typed these symbols ... under the mistaken understanding that Java would interpret the two `+` symbols in the way he / she expected. This may be trivial to you, but it is often baffling to a beginner. – Stephen C Dec 29 '18 at 07:50
  • @StephenC `System.out.println(num1 - num2);` works as expected. I assume that the OP wanted to do the same with `System.out.println(num1 + num2); `, but accidentally forgot to remove the `"= "`-junk characters that messed up the output. But yeah, you're probably right. If someone found a good duplicate target, it's even better. – Andrey Tyukin Dec 29 '18 at 07:51

1 Answers1

1

You are printing the Strings num1 and num2, not the result of the calculation.

When you print out a string ("=" in your case), Java will treat any number added to it as Strings as well).

To solve this, just add your calculation into parentheses to allow Java to calculate them separately:

System.out.println("=" + (num1 + num2));
Zephyr
  • 9,885
  • 4
  • 28
  • 63