0

I am creating a java calculator that evaluates mathematical expression given in string form. I know there has been a question related to this task already posted, but not much of it helps me as a student.

I tried using the substring method and I want to keep using it, I got the "+" working but I can't get the "-" working.

Heres my code:

import java.util.Scanner;
public class Calculator{
public static void main(String[]args){
    Scanner keyboard = new Scanner(System.in);
    String num = keyboard.next();
    for (int x = 0; x < num.length(); x++){
        char n = num.charAt(x);
        if (n == '+'){
            int result = Integer.parseInt(num.substring(0, x)) + Integer.parseInt(num.substring(x, num.length()));
            System.out.println(result);
        }
    }
    String num2 = keyboard.next();
    for (int x = 0; x < num2.length(); x++){
        char n = num2.charAt(x);
        if (n == '-'){
            int result = Integer.parseInt(num.substring(0, x)) - Integer.parseInt(num.substring(x, num.length()));
            System.out.println(result);
        }
    }
}

}

  • 1
    Read the whole line as a string, then read https://stackoverflow.com/questions/3422673/how-to-evaluate-a-math-expression-given-in-string-form – Federico klez Culloca May 12 '20 at 18:07
  • 1
    If the strings are 5+3 and 5-3, you're evaluating 5 + +3 and 5 - -3. You have an off-by-one error in taking the substring of the second operand. Print them out or debug your code, and you'll see the problem. – David Conrad May 12 '20 at 19:16
  • In addition to the off-by-one error, you're also using the `num` String, instead of `num2` String in the second loop. Both of these are fixed in EdenMar's answer. – roninjoe May 12 '20 at 19:26

1 Answers1

1

you should simply add the '-' method inside the same for loop like that:

    public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    String num = keyboard.next();
    for (int x = 0; x < num.length(); x++){
        char n = num.charAt(x);
        if (n == '+'){
            int result = Integer.parseInt(num.substring(0, x)) + Integer.parseInt(num.substring(x, num.length()));
            System.out.println(result);
        }
        else if (n == '-'){
            int result = Integer.parseInt(num.substring(0, x)) - Integer.parseInt(num.substring(x+1, num.length()));
            System.out.println(result);
        }
    }

} 
EdenMar
  • 103
  • 9