-3

Just started learning java and I'm trying to make a calculator with JPanes in the easiest way possible. I can manage to get it to do simple concatenation, but I can't get it to add the entered numbers together. Any help is appreciated.

import javax.swing.*;

public class fiveInputs{
    public static void main (String [] args) {

        java.lang.String num = "";
        java.lang.String num2 = "";
        java.lang.String num3 = "";
        java.lang.String num4 = "";
        java.lang.String num5 = "";

        num = JOptionPane.showInputDialog("First number: ");
        num2 = JOptionPane.showInputDialog("Second number: ");
        num3 = JOptionPane.showInputDialog("Third number: ");
        num4 = JOptionPane.showInputDialog("Fourth number: ");
        num5 = JOptionPane.showInputDialog("Fifth number: ");

        java.lang.String sum = "";

        if (sum.equals(""));
           JOptionPane.showInputDialog (num - num2 - num3 - num4 - num5);

        System.out.println(sum);

    }
}
ElGavilan
  • 6,610
  • 16
  • 27
  • 36
  • 3
    What happens when you try to subtract a String from a String? Also, this if statement `if (sum.equals(""));` does nothing whether or not it is true. – Compass Feb 10 '15 at 21:19
  • See also this [calculator example](http://stackoverflow.com/a/7441804/418556). It uses `ScriptEngine` to evaluate the expression in the text field. – Andrew Thompson Feb 10 '15 at 21:44

1 Answers1

1

You cannot add and subtract strings as if they were numbers. You need to parse them into a numeric type, for example integer, double, etc.

int num = Integer.parseInt(JOptionPane.showInputDialog("First number: "));
int num2 = Integer.parseInt(JOptionPane.showInputDialog("Second number: "));
int num3 = Integer.parseInt(JOptionPane.showInputDialog("Third number: "));
int num4 = Integer.parseInt(JOptionPane.showInputDialog("Fourth number: "));
int num5 = Integer.parseInt(JOptionPane.showInputDialog("Fifth number: "));

Integer.parseInt can throw a NumberFormat exception if you give it something it doesn't regard as a number e.g. abc, an empty string etc. Use this as a starting point for any validation.

Couple of asides

  • java.lang.String, all classes in java.lang are implicity imported, you don't need the package
  • you don't need to declare all your variables at the top of a method like some languages, do it wherever limits their scope the best.
Adam
  • 35,919
  • 9
  • 100
  • 137