import javax.swing.*;
class gui {
public static void main(String[] args) {
//Scanner obj = new Scanner(System.in);
String s = " ";
s = JOptionPane.showInputDialog(null, "enter first value");
String ab = s;
int value1 = Integer.parseInt(ab);
String s2 = " ";
s2 = JOptionPane.showInputDialog(null, "enter second value");
String cd = s2;
int value2 = Integer.parseInt(cd);
JOptionPane.showMessageDialog(null, " the result " + (value1 + value2));
}
}
Asked
Active
Viewed 115 times
-1

guido
- 18,864
- 6
- 70
- 95

Ashir Wiston
- 1
- 1
-
What's the error you are seeing? – xlm Mar 11 '15 at 04:23
-
Also, why do you have `String s = " ";` then overwrite it with the input dialog? Why don't you just do `String s = JOptionPane.showInputDialog(null, "enter first value");`? Same goes with `s2`. – xlm Mar 11 '15 at 04:27
-
error = error cannot find symbol – Ashir Wiston Mar 11 '15 at 04:30
-
error = cannot find a symol – Ashir Wiston Mar 11 '15 at 04:31
-
Please edit your Q and post as much detail as possible on the error. Copy/paste from the error console if you have to. – xlm Mar 11 '15 at 04:33
-
i do before this String s = JOptionpane.showInputDialoge(null,"enter first value"); but error is come same lines. thats whay i m using antoher way. – Ashir Wiston Mar 11 '15 at 04:35
-
You code compiles fine for me... – MadProgrammer Mar 11 '15 at 04:36
-
plz dear can u send me error free my program to see what m do wrong – Ashir Wiston Mar 11 '15 at 04:38
-
I copied and pasted your code into my IDE and works fine – MadProgrammer Mar 11 '15 at 04:41
-
can u end me again fine program of which you did in you ide. – Ashir Wiston Mar 11 '15 at 04:44
1 Answers
1
Integer.parseInt()
can throw an NumberFormatException
, i.e. Integer.parseInt("abc")
. Whilst you don't have to catch it (it's an unchecked exception), you should make sure your code can handle such input. For example, if you do handle it with a catch
:
try {
Integer.parseInt(ab);
} catch (NumberFormatException e) {
// Handle exception i.e. display error
}
Please check out the documentation on Integer.parseInt
here.
Also please see this related question for useful information on unchecked exceptions and why in this case (working with UI) you should probably catch it.
-
1`NumberFormatException` is an unchecked exception (extending from `RuntimeException`), it doesn't "have" to be caught – MadProgrammer Mar 11 '15 at 04:35
-
@MadProgrammer, ah I didn't realise that. Thanks! +1 I'll edit the answer appropriately. – xlm Mar 11 '15 at 04:39