Assignment Chef icon Assignment Chef
All English tutorials

Programming lesson

Mastering Java Console and Swing GUI: A Step-by-Step Tutorial for CSCI 470/502 Assignment 1

Learn how to compile and run Java console programs and build a simple Swing GUI with this detailed tutorial. Perfect for CSCI 470/502 students tackling their first assignment.

Java console program Java Swing GUI tutorial CSCI 470 assignment 1 CSCI 502 first Java programs Add1.java Add2.java Java exception handling Java Scanner input Java JFrame ActionListener Java GUI calculator compile and run Java Java programming for beginners Swing GUI example Java event-driven programming IntelliJ IDEA Java tutorial Java number addition program Java assignment help

Introduction to Your First Java Programs

Welcome to the world of Java programming! If you're enrolled in CSCI 470/502, your first assignment is a gentle introduction to creating, compiling, and running Java applications. This tutorial will walk you through both parts of the assignment: a console-based program (Add1.java) and a Swing GUI program (Add2.java). By the end, you'll have a solid foundation in Java basics, including input handling, exception handling, and event-driven programming. Let's dive in with a trend-inspired analogy: think of Java as the engine behind many popular apps like Spotify or Minecraft — it's robust, cross-platform, and everywhere!

Understanding the Assignment Structure

This assignment is worth 30 points (15 per program). You'll submit two .java files: Add1.java and Add2.java. Make sure to include a documentation box at the top of each file as per your course guidelines. Avoid submitting .class files or files ending with a tilde (~). If you use IntelliJ IDEA, check JetBrains' official tutorial linked in your assignment.

Part 1: Building a Console Program (Add1.java)

The console program reads two numbers as strings, converts them to doubles, and prints their sum. Here's how it works, step by step.

Setting Up the Scanner

Java's Scanner class reads user input from the console. In our example, we create a Scanner object tied to System.in. This is similar to how a gaming console like PlayStation reads controller inputs — it's your program's way of listening to the user.

Scanner sc = new Scanner(System.in);

Reading and Converting Input

The program reads the first number as a String using sc.next(). Then, it attempts to convert that string to a double using Double.parseDouble(). If the input is invalid (e.g., letters), a NumberFormatException is caught, and an error message is printed. This is a common pattern in Java — always validate user input to prevent crashes. Think of it like a banking app checking that you entered a valid amount before processing a transaction.

try {
    num1 = Double.parseDouble(amountStr);
} catch (NumberFormatException nfe) {
    System.out.println("1st number invalid.");
    return;
}

Computing and Displaying the Sum

After successfully converting both numbers, the program calculates the sum and prints it with two decimal places using System.out.printf(). The %.2f format specifier ensures the output looks neat — just like how a finance dashboard displays currency values.

System.out.printf("Sum is: %.2f ", num1 + num2);

Complete Add1.java Code

Here's the full program (as given in the assignment):

import java.util.Scanner;

/** Add1.java
 * Console program to add two numbers.
 */
public class Add1 {
    public static void main(String[] args) {
        String amountStr;
        double num1, num2;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the first number: ");
        amountStr = sc.next();
        try {
            num1 = Double.parseDouble(amountStr);
        } catch (NumberFormatException nfe) {
            System.out.println("1st number invalid.");
            return;
        }
        System.out.println("Enter the second number: ");
        amountStr = sc.next();
        try {
            num2 = Double.parseDouble(amountStr);
        } catch (NumberFormatException nfe) {
            System.out.println("2nd number invalid.");
            return;
        }
        System.out.printf("Sum is: %.2f ", num1 + num2);
    }
}

Part 2: Building a Swing GUI Program (Add2.java)

The second program introduces Java Swing, a toolkit for building graphical user interfaces. You'll create a window with text fields, buttons, and a label. This is like building a simple calculator app that you might see on a smartphone.

Extending JFrame and Implementing ActionListener

Your class Add2 extends JFrame (the main window) and implements ActionListener to handle button clicks. This is a common pattern in Swing — similar to how a viral app like TikTok responds to user taps.

public class Add2 extends JFrame implements ActionListener { ... }

Creating the GUI Components

Inside the class, you declare UI components: two JTextFields for input, a JButton to compute, a JButton to clear, and a JLabel to display the sum. The initComponents() method sets up a JPanel with a GridLayout and adds all components. This layout ensures the UI looks organized — think of it like arranging icons on your smartphone home screen.

private void initComponents() {
    JPanel panel = new JPanel(new GridLayout(4, 2, 5, 5));
    panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    panel.add(new JLabel("First number:"));
    panel.add(num1Field);
    panel.add(new JLabel("Second number:"));
    panel.add(num2Field);
    panel.add(new JLabel("Sum:"));
    panel.add(sumLabel);
    panel.add(addButton);
    panel.add(clearButton);
    add(panel, BorderLayout.CENTER);
}

Handling Button Events

The actionPerformed method checks which button was clicked. For the clear button, it resets all fields. For the add button, it reads the text fields, converts to doubles (with exception handling), and updates the label. This event-driven model is the same concept used in AI chatbots that respond to user queries.

@Override
public void actionPerformed(ActionEvent e) {
    double num1, num2;
    if (e.getSource() == clearButton) {
        num1Field.setText("");
        num2Field.setText("");
        sumLabel.setText("");
    } else {
        try {
            num1 = Double.parseDouble(num1Field.getText());
        } catch (NumberFormatException nfe) {
            sumLabel.setText("1st number invalid.");
            return;
        }
        try {
            num2 = Double.parseDouble(num2Field.getText());
        } catch (NumberFormatException nfe) {
            sumLabel.setText("2nd number invalid.");
            return;
        }
        sumLabel.setText(String.format("%.2f", num1 + num2));
    }
}

Thread Safety with EventQueue.invokeLater

Notice the main method uses EventQueue.invokeLater to create and show the GUI. This ensures the GUI is built on the Event Dispatch Thread (EDT), preventing thread-safety issues. It's like ensuring that only one person at a time updates a shared Google Doc to avoid conflicts.

EventQueue.invokeLater(() -> {
    Add2 frame = new Add2("Sum of Two Numbers");
    frame.createAndShowGUI();
});

Complete Add2.java Code

Here's the full Swing program as provided:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Add2 extends JFrame implements ActionListener {
    private static final long serialVersionUID = 1L;
    private JButton addButton = new JButton("Add Numbers");
    private JButton clearButton = new JButton("Clear Numbers");
    private JTextField num1Field = new JTextField(10);
    private JTextField num2Field = new JTextField(10);
    private JLabel sumLabel = new JLabel();

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            Add2 frame = new Add2("Sum of Two Numbers");
            frame.createAndShowGUI();
        });
    }

    private Add2(String title) {
        super(title);
    }

    private void createAndShowGUI() {
        initComponents();
        addButton.addActionListener(this);
        clearButton.addActionListener(this);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }

    private void initComponents() {
        JPanel panel = new JPanel(new GridLayout(4, 2, 5, 5));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        panel.add(new JLabel("First number:"));
        panel.add(num1Field);
        panel.add(new JLabel("Second number:"));
        panel.add(num2Field);
        panel.add(new JLabel("Sum:"));
        panel.add(sumLabel);
        panel.add(addButton);
        panel.add(clearButton);
        add(panel, BorderLayout.CENTER);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        double num1, num2;
        if (e.getSource() == clearButton) {
            num1Field.setText("");
            num2Field.setText("");
            sumLabel.setText("");
        } else {
            try {
                num1 = Double.parseDouble(num1Field.getText());
            } catch (NumberFormatException nfe) {
                sumLabel.setText("1st number invalid.");
                return;
            }
            try {
                num2 = Double.parseDouble(num2Field.getText());
            } catch (NumberFormatException nfe) {
                sumLabel.setText("2nd number invalid.");
                return;
            }
            sumLabel.setText(String.format("%.2f", num1 + num2));
        }
    }
}

Compiling and Running Your Programs

To compile: use javac Add1.java and javac Add2.java. To run: java Add1 (console) or java Add2 (GUI). If you're using an IDE like IntelliJ IDEA or Eclipse, you can run directly from the IDE. This is similar to how game developers compile their code before testing a new level.

Common Pitfalls and Tips

  • File names must match class names exactly. For example, Add1.java contains public class Add1.
  • Avoid submitting .class or ~ files. Only submit .java files.
  • Always handle exceptions. The try-catch blocks prevent crashes when users enter invalid data.
  • Use meaningful variable names. This improves readability — a practice valued in open-source projects like those on GitHub.

Connecting to Real-World Trends

Java remains a powerhouse in enterprise applications, Android development, and big data. For instance, Netflix uses Java for its recommendation engine, and Amazon Web Services relies on Java for many services. By mastering these basics, you're building skills that apply to high-demand fields like AI and cloud computing. Even the latest AI chatbots like ChatGPT are built on languages that share similar OOP principles.

Conclusion

This assignment gives you hands-on experience with Java's console and GUI capabilities. You've learned to handle user input, manage exceptions, and create interactive windows. As you progress, these fundamentals will help you tackle more complex projects. Happy coding, and remember: every expert was once a beginner!