Search code examples
javaalgorithmmathidemultiplication

Add two numbers instead of combining


I am trying to create a program in which a user can enter 2 numbers and the program will take the 2 numbers and multiply them to get an answer. However, for this specific example, I am simply trying to take 2 numbers from a user and I want Java to add them. eg 1+1=2, instead of 1+1=11.

My code:

import javax.swing.JOptionPane;

public class MultiplicationTables {

    public static void main(String args[]) {
        //declare variables

        String num1;
        String num2;
        int ans=0;

        num1=JOptionPane.showInputDialog(null,"Enter a number");
        num2=JOptionPane.showInputDialog(null,"Enter another number");

        ans=Integer.parseInt(num1);
        ans=Integer.parseInt(num2);


        JOptionPane.showMessageDialog(null,"Your answer is " + (num1+num2));
    }
}

Solution

  • You are using num1 and num2 which are Strings instead of ans which should be your sum as an int. Also you don't add correctly the 2 values into ans.

    public static void main(String args[]){
        String num1 = JOptionPane.showInputDialog(null,"Enter a number");
        String num2 = JOptionPane.showInputDialog(null,"Enter another number");
    
        int ans = Integer.parseInt(num1);
        ans += Integer.parseInt(num2);
    
        JOptionPane.showMessageDialog(null,"Your answer is " + ans);
    }