Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package lab05;
- import java.awt.event.*;
- import java.util.*;
- import javax.swing.*;
- public class ChooseYourOperation {
- public static void main(String[] args) {
- WidgetViewer wv = new WidgetViewer();
- Random rand = new Random();
- int x = rand.nextInt(10); // Generate first random number 0-9 inclusive
- int y = rand.nextInt(10); // Generate second random number 0-9 inclusive
- String text = "x: " + x + " y: " + y; // Ask user what the answer is
- wv.add(new JLabel(text)); // Create text GUI
- String instruction = "Enter an operation number"; // Ask user what the answer is
- wv.add(new JLabel(instruction)); // Create text GUI
- JTextField textField = new JTextField(10); // Store users answer
- wv.add(textField);
- JButton button = new JButton("Press here when you've entered your operation"); // Button for user to hit once entered answer
- wv.addAndWait(button);
- button.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent arg0) {
- int operationNumber = Integer.parseInt(textField.getText()); // Evaluates stored value
- String result = "";
- if (operationNumber >= 1 && operationNumber <= 10) {
- result = String.valueOf(x+y);
- }
- else if (operationNumber % 4 == 0) {
- result = String.valueOf(x-y);
- }
- else if (operationNumber % 5 == 0) {
- result = String.valueOf(x/y);
- }
- else if (operationNumber % 2 == 0) {
- result = String.valueOf((float)x/y);
- }
- else {
- result = String.valueOf(x*y);
- }
- // Ask user what the answer is
- wv.add(new JLabel(result)); // Create text GUI
- }
- });
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement