Console Based Menu

Objects Used:

  • Used scanner class to get user input and make objects
  • Used system class to print out static methods
  • Used the Math Class from Java to create a basic console calculator
import java.util.*;
import java.util.Scanner;

public class Hello {
    
    public static void main(String[] args) {

        Scanner inp = new Scanner(System.in);

        System.out.println("-------------------------");
        System.out.println("Choose one");
        System.out.println("-------------------------");
        System.out.println("1 - Addition");
        System.out.println("2 - Subtraction");
        System.out.println("3 - Multiplication");
        System.out.println("4 - Division");
        System.out.println("-------------------------\n");

        int choose;
        choose = inp.nextInt();
        System.out.println("Enter first number: ");
        int num1;
        num1 = inp.nextInt();
        System.out.println("Enter second number: " + "\n");
        int num2;
        num2 = inp.nextInt();

        int ans;
        switch (choose) {
        case 1:
            System.out.println(add( num1,num2));
            break;
        case 2:
            System.out.println(sub( num1,num2));
            break;      
        case 3:
            System.out.println(mult( num1,num2));
            break;
        case 4:
            System.out.println(div( num1,num2));
            break;
            default:
                System.out.println("Illegal Operation");
        }

    }

    public static int add (int x, int y) {
        int result = x + y;
        System.out.println(x + " + " + y + " equals");
        return result;
    }

    public static int sub (int x, int y) {
        int result = x-y;
        System.out.println(x + " - " + y + " equals");
        return result;
    }

    public static int mult (int x, int y) {
        int result = x*y;
        System.out.println(x + " * " + y + " equals");
        return result;
    }

    public static int div (int x, int y) {
        int result = x/y;
        System.out.println(x + " / " + y + " equals");
        return result;
    }

}
Hello.main(null);
-------------------------
Choose one
-------------------------
1 - Addition
2 - Subtraction
3 - Multiplication
4 - Division
-------------------------

Enter first number: 
Enter second number: 

3 * 3 equals
9

Desktop GUI Menu

Swing and AWT imports allow Java to provide a Graphical User Interface on the desktop.

Other College Board Topics

  • A 1D array is used to store MENUS
  • A Control Structure, if-else if-else, is used to process Menu selection to code that performs related action

Using Objects

  • Javax Swing UI (JFrame)
  • Timer with a TimerTask to allow action to repeatedly occur without halting thread.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Timer;
import java.util.TimerTask;
// Graphical-User-Interface for Desktop in Java using Java Swing. 
public class MenuJFrame extends JFrame implements ActionListener {
    private JFrame frame;
    private JMenuBar menubar;
    private JMenu menu;
    private JLabel message = new JLabel("Click on Menu to select an action.");
    public final String[] MENUS = { // 1D Array of Menu Choices
        "CSA", "COLORS", "Loading...",  
    };
    // Statics to assist with timer and messaging, single copy (no instance)
    private	static int delay = 10;
    private	static int step = 1;
    private static String hashes = "";

    // Constructor enables the Frame instance, the object "this.frame"
    public MenuJFrame(String title) {
	    // Initializing Key Objects
        frame = new JFrame(title);
	    menubar = new JMenuBar();
	    menu = new JMenu("Menu");

        // Initializing Menu objects and adding actions
        for (String mx : MENUS) {
            JMenuItem m = new JMenuItem(mx);
            m.addActionListener(this);
            menu.add(m); 
        }

        // Adding / Connecting Objects
        menubar.add(menu);
        frame.setJMenuBar(menubar);
        frame.add(message);

        // Sets JFrame close operation to Class variable JFrame.EXIT_ON_CLOSE
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        // set the size of window based on objects
        frame.setSize(700,400);

        // helps set the window to center of screen
        frame.setLocationRelativeTo(null);

        // makes the frame object visible according to properties previously set
        frame.setVisible(true);  // flow of control shifts to frame object
    }

    public static void centreWindow(Window frame) {
        Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
        int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
        frame.setLocation(x, y);
    }

    // event from user selecting a menu option
    public void actionPerformed(ActionEvent e) {
        // local variable to ActinEvent
        String selection = e.getActionCommand();  // menu selection
        String msg; // local variable to create response from action
        final String[] COLORS = {"Red", "Green", "Blue", "Yellow", "Purple"};  // add more colors here
 	    final String start_msg = "<html>";  // html building
       	final String end_msg = "</html>";
       	final String hash = "$";

        // run code based on the menuItem that was selected
        if ( selection.equals(MENUS[0]) ) {  // Hello Action
            msg = "CSA IS AWESOME!";
            message.setText(msg);
        } else if ( selection.equals(MENUS[1]) ) { // Color Action
            msg = start_msg + "<p>" + selection + "</p>";
            for (String color : COLORS) {
                msg += "<font color=" + color + ">" + color + " </font>";
            }
            msg += end_msg;
            message.setText(msg);
        } else {  // Loading Bar Action
	    String loading = "<p>Loading</p>";
            // Code to run on a Timer
            Timer timer = new Timer();
            TimerTask task = new TimerTask() {
                public void run() {  // Method for TimerTask
                    // Static and Local variables used to manage message building
                    int random = (int) (Math.random() * COLORS.length);  // random logic
                    MenuJFrame.hashes +=  "<font color=" + COLORS[random] + ">" + hash + "</font>";
                    String msg = start_msg + loading + hashes + end_msg;
                    message.setText(msg);
                    
	  	            // Shutdown timer and reset data
                    if(MenuJFrame.step++ > MenuJFrame.delay) {
                        MenuJFrame.step = 1; MenuJFrame.hashes="";
                        timer.cancel();
                    }
                };
            };
            // Schedule task and interval
            timer.schedule(task, 200, 200);
            message.setText(start_msg + loading + hash + end_msg);  // prime/initial display
        }
    }

    // Driver turn over control the GUI
    public static void main(String[] args) {
        // Activates an instance of MenuJFrame class, which makes a JFrame object
        new MenuJFrame("Menu");
    }
}
MenuJFrame.main(null);

Hacks

Explain where a Class is defined

  • A class is defined where you add variables, objects or methods to your code
public class // Classname

Explain where an instances of a Class is defined

  • An instance is defined in the main class
  • For example, on Code.org we initiated an instance with
PainterPlus myPainter = new PainterPlus();

Explain where an object is calling a method

  • An object is calling a method when an action needs to be performed for the code to run.
  • Calling a method on code.org
myPainter.paint("white");

Describe Console, GUI differences, or Code.org differences

  • Console

    • User enters input and get respective outputs
    • Not as visual
    • Requires very good understanding of script and syntax
    • Examples: BASH, Terminal, Command Prompt, Kali linux
  • GUI

    • Graphical User Interface
    • More visual interface
    • User-friendly
    • Examples: iOS, Android, MacOS, Windows
  • code.org

    • Introductory platform
    • Graphical representation of what code does with the syntax of the language