0

I just started writing this basic text-based calculator in Java and I found into a problem when I ran the adding portion, when I add 2 numbers, say '9' and '9', the answer comes out to 99 instead of 18, as it should. Is it because I'm not storing integers, I'm storing the user's input as strings. Thank you, I appreciate any help. As you can probably tell, I'm rather new to coding.

import java.util.Scanner;
import java.lang.String;

public class calc {
    public static void main(String[] args) throws InterruptedException {
        while (true) {
            Scanner in = new Scanner(System.in);
            System.out.println("Type in what you would like to do: Add, Subtract, Multiply, or Divide");
            String input = in.nextLine();
            if (input.equalsIgnoreCase("Add")) {
                System.out.println("Type in your first number:");

                String add1 = in.nextLine();
                System.out.println("Type in your second number");
                String add2 = in.nextLine();

                String added = add1 + add2;
                System.out.println("Your answer is:" + added);
            }
            else if(input.equalsIgnoreCase("Subtract")) {
                System.out.println("Type in your first number:");
            }
            else if(input.equalsIgnoreCase("Multiply")) {
                System.out.println("Type in your first number:");
            }
            else if(input.equalsIgnoreCase("Divide")) {
                System.out.println("Type in your first number:");
            }
            else {
                System.out.println("This was not a valid option");
            }
        }
    }
}
Stefan Dollase
  • 4,530
  • 3
  • 27
  • 51
Josh P
  • 29
  • 5
  • Yes, it is because the "+" operator on a String is String concatination. You need to convert to intergers or doubles, or whatever. Be aware of overflow issues as well. Divide with integers will probably not do what you expect, so consider floats or doubles. – KevinO Apr 03 '16 at 19:27

2 Answers2

3

You are trying to add two strings. This will just put the strings next to each other. If you want to add them you need to parse them as doubles first. Try:

            System.out.println("Type in your first number:");
            double add1 = Double.parseDouble(in.nextLine());
            System.out.println("Type in your second number");
            double add2 = Double.parseDouble(in.nextLine());

            double added = add1 + add2;
            System.out.println("Your answer is:" + added);
Josh P
  • 29
  • 5
nhouser9
  • 6,730
  • 3
  • 21
  • 42
  • While this approach solves the addition question (modulo overflow issues), note the code has room for a division, and integer division will not perform as expected. – KevinO Apr 03 '16 at 19:31
2

You need to convert the String to an int value for the addition. Do something like this:

Integer result = Integer.parseInt(add1) + Integer.parseInt(add2)

Adam Rice
  • 880
  • 8
  • 20