Write A Complete Program For The Following Specifications: 1 ✓ Solved
Write a complete program for the following specifications: 1
Write a complete program for the following specifications:
- Implement a SerialNumber class that takes a software serial number in the form LLLLL-DDDD-LLLL where each L is a letter and each D is a digit, extracts the three groups, and validates them. Examples: String serial1 = "GHTRJ-8975-AQWR"; // Valid String serial2 = "GHT7J-8975-AQWR"; // Invalid String serial3 = "GHTRJ-8J75-AQWR"; // Invalid String serial4 = "GHTRJ-8975-AQ2R"; // Invalid
- Create a GUI that displays a frame containing three JLabels, each showing a distinct random card image chosen from image/card/1.png through image/card/54.png.
- Create a Java GUI monthly payment calculator with JTextFields for principal, annual rate (%), and term (years) and a Calculate JButton. Use the formula Monthly Pay = [rate + rate/((1+rate)^months - 1)] × principal, where rate means annual rate/1200 and months = years × 12. Display monthly payment, total payment, and interest expense. Example: principal 12200, rate 7%, years 5 → monthly 241.57, total 14494.48, interest 2294.48.
- Write a program that reads data.txt with lines formatted "First Last" and writes email.txt with lines formatted "last_first@example.com" (lowercase, underscore between names).
Paper For Above Instructions
Overview
This document provides complete Java solutions to four compact tasks: (A) a SerialNumber class that parses and validates serial numbers in the form LLLLL-DDDD-LLLL; (B) a Swing GUI that displays three distinct randomly selected card images from a set of 54 images; (C) a Swing monthly-payment calculator using the provided formula; and (D) a simple file-processing utility that converts "First Last" lines from data.txt into "last_first@example.com" entries in email.txt. Each solution includes code and testing notes. The implementations use standard Java SE APIs for regex, Swing UI, randomization, file I/O, and formatting [1][2].
Task A — SerialNumber Class
Approach: Use a regular expression to validate the format and methods to extract the three groups. The regex ensures 5 letters, dash, 4 digits, dash, 4 letters. Letters are A–Z (case-insensitive) and digits 0–9. Example inputs are validated against this pattern [2].
public class SerialNumber {
private final String group1;
private final String group2;
private final String group3;
public SerialNumber(String serial) {
if (serial == null) throw new IllegalArgumentException("Serial is null");
String s = serial.trim();
// Pattern: 5 letters - 4 digits - 4 letters
if (!s.matches("(?i)^[A-Z]{5}-\\d{4}-[A-Z]{4}$")) {
throw new IllegalArgumentException("Invalid serial format: " + serial);
}
String[] parts = s.split("-");
group1 = parts[0];
group2 = parts[1];
group3 = parts[2];
}
public String getGroup1() { return group1; }
public String getGroup2() { return group2; }
public String getGroup3() { return group3; }
public boolean isValid() {
// Pattern already guarantees validity, but helper if needed
return group1.matches("(?i)^[A-Z]{5}$") &&
group2.matches("^\\d{4}$") &&
group3.matches("(?i)^[A-Z]{4}$");
}
@Override
public String toString() {
return group1 + "-" + group2 + "-" + group3;
}
// Example usage:
public static void main(String[] args) {
String[] tests = {"GHTRJ-8975-AQWR", "GHT7J-8975-AQWR", "GHTRJ-8J75-AQWR", "GHTRJ-8975-AQ2R"};
for (String t : tests) {
try {
SerialNumber sn = new SerialNumber(t);
System.out.println(t + " -> valid, groups: " + sn.getGroup1() + ", " + sn.getGroup2() + ", " + sn.getGroup3());
} catch (IllegalArgumentException ex) {
System.out.println(t + " -> invalid (" + ex.getMessage() + ")");
}
}
}
}
Notes: The (?i) flag makes the regex case-insensitive. This class provides safe parsing and clear error messages [2].
Task B — Display Three Distinct Random Card Images (Swing)
Approach: Load icons with ImageIcon, choose three distinct random integers from 1..54, and set them to three JLabels inside a JFrame. Ensure images exist at image/card/{n}.png. Use a layout that displays icons nicely (e.g., FlowLayout or GridLayout). This is standard Swing image handling and randomization [3][4].
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.nio.file.*;
public class CardDisplay {
public static void showCards() {
JFrame frame = new JFrame("Three Random Cards");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
// pick 3 distinct numbers from 1..54
List deck = new ArrayList();
for (int i = 1; i
Collections.shuffle(deck);
for (int i = 0; i
int n = deck.get(i);
String path = "image/card/" + n + ".png";
ImageIcon icon = new ImageIcon(path);
JLabel label = new JLabel(icon);
label.setBorder(BorderFactory.createLineBorder(Color.GRAY));
frame.add(label);
}
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(CardDisplay::showCards);
}
}
Notes: If images are large, consider scaling icons for consistent size. Use Resource loading for packaged applications [1][3].
Task C — Monthly Payment Calculator GUI
Approach: Provide a small Swing form with JTextFields for Principal, Annual Rate (%), and Years, plus a Calculate JButton. Compute using the specified formula:
monthlyRate = annualRate / 1200; months = years 12; monthlyPayment = (monthlyRate + monthlyRate / (Math.pow(1+monthlyRate, months) - 1)) principal;
Round outputs to two decimals and display Monthly Payment, Total Payment, and Interest Expense. Use DecimalFormat for user-friendly presentation [5].
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
public class MonthlyCalculator {
private static DecimalFormat df = new DecimalFormat("#0.00");
public static void createAndShow() {
JFrame frame = new JFrame("Monthly Payment Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(6, 2, 6, 6));
JTextField principalField = new JTextField("12200");
JTextField rateField = new JTextField("7");
JTextField yearsField = new JTextField("5");
JLabel monthlyLabel = new JLabel("Monthly Payment:");
JLabel totalLabel = new JLabel("Total Payment:");
JLabel interestLabel = new JLabel("Interest Expense:");
JLabel monthlyVal = new JLabel();
JLabel totalVal = new JLabel();
JLabel interestVal = new JLabel();
JButton calc = new JButton("Calculate");
calc.addActionListener(e -> {
try {
double principal = Double.parseDouble(principalField.getText().trim());
double annualRate = Double.parseDouble(rateField.getText().trim());
int years = Integer.parseInt(yearsField.getText().trim());
double rate = annualRate / 1200.0;
int months = years * 12;
double monthly = (rate + rate / (Math.pow(1 + rate, months) - 1.0)) * principal;
double total = monthly * months;
double interest = total - principal;
monthlyVal.setText("$" + df.format(monthly));
totalVal.setText("$" + df.format(total));
interestVal.setText("$" + df.format(interest));
} catch (Exception ex) {
JOptionPane.showMessageDialog(frame, "Please enter valid numbers.", "Input Error", JOptionPane.ERROR_MESSAGE);
}
});
frame.add(new JLabel("Principal:")); frame.add(principalField);
frame.add(new JLabel("Annual Rate (%):")); frame.add(rateField);
frame.add(new JLabel("Term (years):")); frame.add(yearsField);
frame.add(calc); frame.add(new JLabel());
frame.add(monthlyLabel); frame.add(monthlyVal);
frame.add(totalLabel); frame.add(totalVal);
frame.add(interestLabel); frame.add(interestVal);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(MonthlyCalculator::createAndShow);
}
}
Testing with the provided example (12200, 7%, 5 years) produces values very close to the example numbers when using the specified formula [5].
Task D — Convert data.txt to email.txt
Approach: Read data.txt line by line, split each line into first and last name (trim whitespace), build an email string last_first@example.com in lowercase, and write lines to email.txt. Use try-with-resources and UTF-8 encoding for safety [6].
import java.io.*;
import java.nio.file.*;
import java.util.*;
public class EmailGenerator {
public static void main(String[] args) throws IOException {
Path in = Paths.get("data.txt");
Path out = Paths.get("email.txt");
try (BufferedReader br = Files.newBufferedReader(in);
BufferedWriter bw = Files.newBufferedWriter(out)) {
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.trim().split("\\s+");
if (parts.length >= 2) {
String first = parts[0].toLowerCase();
String last = parts[1].toLowerCase();
String email = last + "_" + first + "@example.com";
bw.write(email);
bw.newLine();
}
}
}
}
}
Notes: This simple implementation assumes each line has at least two tokens; for more robust handling, permit multi-part last names and sanitize characters [6].
Conclusion and Testing
The four components above provide clear, modular implementations suitable for classroom assignments. The SerialNumber class uses a strict regex for exact validation; the card display uses randomized selection without duplicates; the monthly calculator uses the supplied formula and displays currency-formatted outputs; and the email generator reads and writes plain text files safely. Each section uses standard Java APIs and can be enhanced with further validation and error handling as needed [1][2][3][5][6].
References
- Oracle. "The Java Tutorials." https://docs.oracle.com/javase/tutorial/ — Core Java tutorial covering Swing, I/O, and utilities.
- Oracle. "Pattern (Regular Expressions) - Java Platform SE 8." https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html — Regex usage and examples.
- Oracle. "How to Use Icons" (Swing). https://docs.oracle.com/javase/tutorial/uiswing/components/icon.html — ImageIcon and resource loading guidance.
- Bloch, Joshua. "Effective Java." Addison-Wesley, 3rd Edition, 2018. — Best practices for Java programming.
- Horstmann, Cay. "Core Java Volume I — Fundamentals." Prentice Hall. — Swing and core APIs reference.
- Oracle. "Working with Files (NIO)." https://docs.oracle.com/javase/tutorial/essential/io/file.html — File I/O best practices and examples.
- Stack Overflow community examples for random shuffling and distinct selection. https://stackoverflow.com/questions/ — Practical patterns for Collections.shuffle use.
- Deitel, Paul; Deitel, Harvey. "Java: How to Program." Pearson. — GUI examples and formatting.
- Oracle. "DecimalFormat (Java Platform SE 8)." https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html — Formatting numeric outputs.
- Gamma, Erich et al. "Design Patterns: Elements of Reusable Object-Oriented Software." Addison-Wesley. — Useful for modular design discussion.