Ezwan Abid
Ezwan Abid

Reputation: 37

incompatible types error

import javax.swing.JOptionPane;
public class Result
{
public static void main (String[] args)
{
    int numa;
    int numb;
    int sum;
    String num1 = JOptionPane.showInputDialog(null,"Enter 1st Number: ");
    numa=Integer.parseInt(num1);
    String num2 = JOptionPane.showInputDialog(null,"Enter 2nd Number: ");
    numb=Integer.parseInt(num2);
    {
        sum=num1+num2;
    }

    if (sum>=10)
        JOptionPane.showMessageDialog(null,"Congratulations"+sum);
        else if(sum<10)
            JOptionPane.showMessageDialog(null,"the sum of the number less than 10");
            else if(sum>100)
                System.exit(7);
}
}

Upvotes: 0

Views: 150

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1503469

This line:

sum=num1+num2;

is trying to add two strings together and make an int.

Instead, you want:

sum = numa + numb;

In other words, take the values you've just parsed from the strings, and add those together.

Additionally, I'd suggest:

  • Where possible, declare variables at the point where you first use them (typically assignment)
  • Don't add braces just for the sake of it (e.g. for this sum line) but...
  • ... do add braces to all if blocks for clarity
  • Indent all code appropriately (there should never be two braces lining up as per the end of your method)
  • Unless you really need to use Swing, don't bother - this app would be simpler if it took input from the console and just wrote the answer to the console, instead of showing a message box.

Upvotes: 4

Cory Kendall
Cory Kendall

Reputation: 7324

sum = numa + numb

You were trying to add the two strings.

Edit: skeeted again!

Upvotes: 2

Related Questions