I am writing an application for class. The user is prompted to enter a number, then select what to do what that number. I'm using JPanel and JOptionpane for input and console for output.
The application is supposed to: prompt for input, ask for what to do with the input, display results, prompt for input again.
I have everything the way I want it, except I cannot get the input prompt to loop correctly. Right now when you compile the code your prompted for the input, then you can select what to do with it as many times as you like before closing the application. I'm not sure how to exit the JPanel and ask for another user input.
Here is my code so far:
package phase4individualproject;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
*
* @author Weylin N. Bowman.
*/
public class project4 {
public static void main(String[] args) {
JFrame Math = new JFrame("Calculator");
Math.setSize(300, 150);
Math.setLocation(200,200);
Math.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent w) {System.exit(0); }
});
JPanel options = new JPanel();
final ButtonGroup mathOptions = new ButtonGroup();
JRadioButton radioButton;
options.add(radioButton = new JRadioButton("Square"));
radioButton.setActionCommand("1");
mathOptions.add(radioButton);
options.add(radioButton = new JRadioButton("Cube"));
radioButton.setActionCommand("2");
mathOptions.add(radioButton);
options.add(radioButton = new JRadioButton("Double"));
radioButton.setActionCommand("3");
mathOptions.add(radioButton);
options.add(radioButton = new JRadioButton("Halve"));
radioButton.setActionCommand("4");
mathOptions.add(radioButton);
JPanel submit = new JPanel();
JButton calc = new JButton("Calculate");
submit.add(calc);
Container content = Math.getContentPane();
content.setLayout(new GridLayout(3, 1));
content.add(options);
content.add(submit);
String number;
int close = 0;
do{
number = JOptionPane.showInputDialog("Please enter any number.");
final int num = Integer.parseInt(number);
calc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("You entered: " + num);
String selected = mathOptions.getSelection().getActionCommand();
int selectedNum = Integer.parseInt(selected);
if(selectedNum == 1){
System.out.println(num * num);
}
else if(selectedNum == 2){
System.out.println(num * num * num);
}
else if(selectedNum == 3){
System.out.println(num * 2);
}
else if(selectedNum == 4){
System.out.println(num/2);
System.exit(1);
}
else{
System.exit(1);
}
}
});
Math.setVisible(true);
}while(false);
}
}