Ok So I'm trying to create a very simple java Calculator Using JOptionPane method, This is mainly just an experiment but back to the question. How come When my First JOptionPane Window comes up it doesn't continue to the second window which should say "Enter an Operator"? Any Help appreciated! Thanks!
import javax.swing.JOptionPane;
import java.util.*;
public class Calculator {
double a1, a2;
char b1;
public void Cal() {
Scanner scan = new Scanner(System.in);
Scanner in = new Scanner(System.in);
JOptionPane.showInputDialog("Enter Ur First Number ");
a1 = scan.nextInt();
JOptionPane.showInputDialog("Enter an Operator");
b1 = in.next().charAt(0);
if (b1 == '-' || b1 == '+' || b1 == '*' || b1 == '/') {
}
else {
System.out.println("Invalid Input");
}
JOptionPane.showInputDialog("Enter Ur Second Number");
a2 = scan.nextInt();
JOptionPane.showMessageDialog(null, a1 + b1 + a2);
}
}
This line a1 = scan.nextInt();
expects some input from command line. Until you do not enter anything on command line the program blocks.
It is not a good idea to mix Graphical UI elements (i.e. JOptionPane
) with non-GUI elements (i.e. Scanner
).
For a command line version use System.out.println
for outputs to the user and Scanner
for input (like you already do). For a Swing version use a full GUI approach by using javax.swing.JWindow
, for example. JOptionPane
is really just meant for popping up options from a graphical context (like a window or frame). In your example, there is no graphical context.