Chapter 10 20 marks
Build an application that can determine payments for employees and invoices, first create interface Payable, which contains method
getPaymentAmount that returns a double amount that must be paid for an object of any class that implements the interface.
Create class Invoice which implements interface Payable to represent a simple invoice that contains billing information for only one kind of part.
The class declares private instance variables partNumber, partDescription, quantity and pricePerItem. Class Invoice also contains a constructor ,
get and set methods that manipulate the class’s instance variables and toString method that returns a String representation of an Invoice object.
Methods setQuantity and setPricePerItem ensure that quantity and pricePer Item obtain only nonnegative values. Class Invoice that calculates the
total payment required to pay the invoice. The method multiplies the values of quantity (obtained through the appropriate getmethods) and pricePer
Item and returns the result.
Also create abstract class Employee that implements interface Payable. The class declares private instance variables firstName, lastName and
socialSecurityNumber. Class Employee contains a constructor, get and set methods that manipulate the class’s instance variables and toString
method that returns employee’s information.
And then, SalariedEmployee class that extends Employee and fulfills superclass Employee’s contract to implement Payable method
getPaymentAmount that return weeklySalary. It has weeklySalary as its own instance’s variable and implements its properties. Finally, construct
PayableInterfaceTest that interface Payable can be used to proccess a set of Invoices and Employees polymorphically in a single application.
Payable Class
package revision1.chapter10;
public interface Payable {
double getPaymentAmount();
}
Invoice Class
package revision1.chapter10;
public class Invoice implements Payable{
private String partNumber;
private String partDescription;
private int quantity;
private double pricePerItem;
public Invoice(String partNumber, String partDescription, int quantity, double pricePerItem) {
this.partNumber = partNumber;
this.partDescription = partDescription;
this.quantity = quantity;
this.pricePerItem = pricePerItem;
}
public String getPartNumber() {
return partNumber;
}
public void setPartNumber(String partNumber) {
this.partNumber = partNumber;
}
public String getPartDescription() {
return partDescription;
}
public void setPartDescription(String partDescription) {
this.partDescription = partDescription;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
if(quantity > 0)
this.quantity = quantity;
else
System.out.println("Quantity must be greater than 0");
}
public double getPricePerItem() {
return pricePerItem;
}
public void setPricePerItem(double pricePerItem) {
if(pricePerItem > 0.0)
this.pricePerItem = pricePerItem;
else
System.out.println("Price per Item must be greater than 0.0");
}
@Override
public String toString() {
return String.format("%s:\n%s: %s\n%s: %s\n%s: %s\n%s: $%,.2f",
"Invoice",
"Part Number", partNumber,
"Description", partDescription,
"Quantity", quantity,
"Price per Item", pricePerItem);
}
@Override
public double getPaymentAmount() {
return getQuantity() * getPricePerItem();
}
}
Employee Class
package revision1.chapter10;
public abstract class Employee implements Payable{
private String firstName;
private String lastName;
private String socialSecurityNumber;
public Employee(String firstName, String lastName, String socialSecurityNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.socialSecurityNumber = socialSecurityNumber;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getSocialSecurityNumber() {
return socialSecurityNumber;
}
public void setSocialSecurityNumber(String socialSecurityNumber) {
this.socialSecurityNumber = socialSecurityNumber;
}
@Override
public String toString() {
return String.format("%s %s\n%s: %s", firstName, lastName, "Social Security Number",
socialSecurityNumber);
}
}
SalariedEmployee Class
package revision1.chapter10;
public class SalariedEmployee extends Employee{
private double weeklySalary;
public SalariedEmployee(String firstName, String lastName, String socialSecurityNumber, double
weeklySalary) {
super(firstName, lastName, socialSecurityNumber);
this.weeklySalary = weeklySalary;
}
public double getWeeklySalary() {
return weeklySalary;
}
public void setWeeklySalary(double weeklySalary) {
this.weeklySalary = weeklySalary;
}
@Override
public String toString() {
return String.format("%s: %s\n%s: $%,.2f",
"Salaried Employee",
super.toString(),
"Weekly Salary", weeklySalary);
}
@Override
public double getPaymentAmount() {
return getWeeklySalary();
}
}
PayableInterfaceTest Class
package revision1.chapter10;
public class PayableInterfaceTest {
public static void main(String[] args) {
Payable[] payableObjects = new Payable[2];
payableObjects[0] = new Invoice("01234", "seat", 2, 375.00);
payableObjects[1] = new SalariedEmployee("Lisa", "Barnes", "888-88-8888", 1200.00);
System.out.println("Invoices and Employees processed polymophically:\n");
for (Payable currentPayable : payableObjects) {
System.out.printf("%s\n%s: $%,.2f\n\n",
currentPayable.toString(),
"payment due", currentPayable.getPaymentAmount());
}
}
}
Chapter 11 10 marks
Write a java application which uses exception handling to process any ArithmeticExceptions and InputMistmatchExceptions. The application
prompts the user for two integers and passes them to method quotient,which calculates the quotient and returns an int result. This application uses
exception handling so that if the user makes a mistake, the program catches and handles the exception in this case, allowing the user to enter the
input again. Test the result in different ways.
Arithmetic Class
package revision1.chapter11;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Arithmetic {
public static int quotient(int numerator, int denominator) throws ArithmeticException{
return numerator/denominator;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numerator, denominator, result;
boolean loopContinue = true;
do {
try {
System.out.print("Enter an integer numerator: ");
numerator = input.nextInt();
System.out.print("Enter an integer denominator: ");
denominator = input.nextInt();
result = quotient(numerator, denominator);
System.out.printf("Result: %d / %d = %d", numerator, denominator, result);
loopContinue = false;
} catch (ArithmeticException a) {
System.err.printf("\nException: %s\n", a);
System.out.println("Zero is an invalid denominator. Please try again.\n");
} catch (InputMismatchException i) {
System.err.printf("\nException: %s\n", i);
input.nextLine();
System.out.println("You must enter integer. Please try again.\n");
}
}while(loopContinue);
input.close();
}
}
Write a program that demonstrates how various exceptions are caught with catch ( Exception exception ). This time, define classes ExceptionA
(which inherits from class Exception) and ExceptionB (which inherits from class ExceptionA). In your program, create try blocks that throw
exceptions of types ExceptionA, ExceptionB, NullPointerException and IOException. All exceptions should be caught with catch blocks
specifying type Exception.
ExceptionA Class
package revision1.chapter11;
public class ExceptionA extends Exception{
public ExceptionA(String message) {
super(message);
}
}
ExceptionB Class
package revision1.chapter11;
public class ExceptionB extends ExceptionA{
public ExceptionB(String message) {
super(message);
}
}
ExceptionTest Class
package revision1.chapter11;
import java.io.IOException;
public class ExceptionTest {
public static void main(String[] args) {
try {
throwExceptionA();
} catch (Exception e) {
System.out.println("Catch Exception: " + e.getMessage());
}
try {
throwExceptionB();
} catch (Exception e) {
System.out.println("Catch Exception: " + e.getMessage());
}
try {
throwNullPointer();
} catch (Exception e) {
System.out.println("Catch Exception: " + e.getMessage());
}
try {
throwIOException();
} catch (Exception e) {
System.out.println("Catch Exception: " + e.getMessage());
}
}
private static void throwExceptionA() throws ExceptionA {
throw new ExceptionA("ExceptionA occured");
}
private static void throwExceptionB() throws ExceptionB {
throw new ExceptionB("ExceptionB occured");
}
private static void throwNullPointer() {
throw new NullPointerException("NullPointerException occured");
}
private static void throwIOException() throws IOException {
throw new IOException("IOException occured");
}
}
Chapter 14 10 marks
Create the following GUI. You do not have to provide any functionality.
Calculator Class
package revision1.chapter14;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Calculator extends JFrame{
private static final String[] num = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+"
};
public Calculator() {
super("Calculator");
JPanel container = new JPanel();
JPanel display = new JPanel();
JTextField outputField = new JTextField(17);
JPanel numPad = new JPanel(new GridLayout(4, 4, 3, 3)); // row, column, hgap, vgap
for (int i = 0; i < num.length; i++) {
numPad.add(new JButton(num[i]));
}
add(container);
container.add(display);
display.add(outputField);
container.add(numPad);
}
public static void main(String[] args) {
Calculator test = new Calculator();
test.setVisible(true);
test.setSize(200, 200);
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Write a temperature-conversion application that converts from Fahrenheit to Celsius. The Fahrenheit temperature should be entered from the
keyboard (via a JTextField). A JLabel should be used to display the converted temperature. Use the following for mula for the conversion: Celsius
= ( Fahrenheit– 32 ) × 5 / 9
TempConversion Class
package revision1.chapter14;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class TempConversion extends JFrame{
public double FtoC(double F) {
return (F - 32) * 5 / 9;
}
public TempConversion() {
super("Temperature Conversion");
JPanel container = new JPanel(new BorderLayout(5,5)); // hgap, vgap
JLabel title = new JLabel("Fahrenheit to Celsius Conversion", SwingConstants.CENTER);
JPanel conversion = new JPanel();
JTextField input = new JTextField(10);
JLabel result = new JLabel("??");
input.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
double inputTemp = 0.0f;
double conversion = 0.0f;
if (e.getSource() == input) {
try {
inputTemp = Double.parseDouble(e.getActionCommand());
} catch (NumberFormatException n) {
JOptionPane.showMessageDialog(null, n);
}
conversion = FtoC(inputTemp);
result.setText(String.format("%.2f", conversion));
}
}
}
);
add(container);
container.add(conversion);
conversion.add(title);
conversion.add(input);
conversion.add(result);
}
public static void main(String[] args) {
TempConversion test = new TempConversion();
test.setVisible(true);
test.setSize(300, 150);
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Chapter 20 10 marks
Write a java program uses an ArrayList demonstrate several capabilities of interface Collection. The program places two Color arrays (colors and
removeColors) in ArrayLists and uses an Iterator to remove elements in the second ArrayList collection from the first.
ArrayList Class
package revision1.chapter20;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
public class ArrayListTest {
public static void main(String[] args) {
String[] colors = {"MAGENTA", "RED", "WHITE", "BLUE", "CYAN"};
List<String> list = new ArrayList<>();
for (String color : colors)
list.add(color);
String[] rcolors = {"RED", "WHITE", "BLUE"};
List<String> rlist = new ArrayList<>();
for (String rcolor : rcolors)
rlist.add(rcolor);
System.out.print("ArrayList: ");
for (String color : list)
System.out.printf("%s ", color);
removeColors(list, rlist);
System.out.print("\n\nArrayList after calling removeColors: ");
for (String color : list)
System.out.printf("%s ", color);
}
private static void removeColors(Collection<String> c1, Collection<String> c2) {
Iterator<String> iterator = c1.iterator();
while(iterator.hasNext()) {
if(c2.contains(iterator.next()))
iterator.remove();
}
}
Write a program that determines and prints the number of duplicate words in a sentence. Treat uppercase and lowercase letters the same. Ignore
punctuation.
CountDuplicate Class
package revision1.chapter20;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class CountDuplicate {
public static void main(String[] args) {
String sentence, cleanedSentence;
Scanner input = new Scanner(System.in);
System.out.print("Enter a sentence: ");
sentence = input.nextLine();
cleanedSentence = sentence.toLowerCase().replaceAll("[^a-zA-Z\\s]", "");
String[] words = cleanedSentence.split("\\s+");
Map<String, Integer> wordCount = new HashMap<>();
for (String word : words)
wordCount.put(word, wordCount.getOrDefault(word,0) + 1);
int duplicateCount = 0;
System.out.print("\nDuplicate words in the sentence: ");
for (Map.Entry<String, Integer>entry : wordCount.entrySet()) {
if (entry.getValue() > 1) {
System.out.println(entry.getKey() + " - " + entry.getValue() + " times");
duplicateCount++;
}
}
System.out.println("Total number of duplicate words: " + duplicateCount);
input.close();
}
}
Chapter 25 20 marks
Develop a Java Swing program that requires the use of JTabbedPane to organize content into multiple tabs. The program creates a GUI with three
tabs labeled "Tab One", "Tab Two", and "Tab Three". Tab One is a panel with a label "panel one" and a gray background. Tab Two is a panel with
a label "panel two" and a yellow background. Tab Three is a panel with a BorderLayout, where: The North, South, East, and West sections contain
labels indicating their position. The Center section contains a label "panel three". Also write a test class that demonstrates capabilities of
JTabbedPane .
TabbedPaneFrame Class
package revision1.chapter25;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingConstants;
public class TabbedPaneFrame extends JFrame{
public TabbedPaneFrame() {
super("Tabbed Pane Demo");
JTabbedPane pane = new JTabbedPane();
JPanel panel1 = new JPanel();
JLabel label1 = new JLabel("Panel one", SwingConstants.CENTER);
JPanel panel2 = new JPanel();
panel2.setBackground(Color.YELLOW);
JLabel label2 = new JLabel("Panel two", SwingConstants.CENTER);
JPanel panel3 = new JPanel(new BorderLayout());
panel3.add(new JButton("North"), BorderLayout.NORTH);
panel3.add(new JButton("West"), BorderLayout.WEST);
panel3.add(new JButton("East"), BorderLayout.EAST);
panel3.add(new JButton("South"), BorderLayout.SOUTH);
JLabel label3 = new JLabel("Panel three", SwingConstants.CENTER);
add(pane);
pane.addTab("Tab One", null, panel1, "Frst Panel");
pane.addTab("Tab Two", null, panel2, "Second Panel");
pane.addTab("Tab Three", null, panel3, "Third Panel");
panel1.add(label1);
panel2.add(label2);
panel3.add(label3);
}
}
TabbedPaneFrameTest Class
package revision1.chapter25;
import javax.swing.JFrame;
public class TabbedPaneFrameTest {
public static void main(String[] args) {
TabbedPaneFrame test = new TabbedPaneFrame();
test.setVisible(true);
test.setSize(300, 200);
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Write a Java Swing program using GridBagLayout to create a GUI similar to the one shown in the image. . The layout should include: A TextField
at the top. A row of three buttons labeled "zero", "one", and "two". A label "Copper" positioned beneath the buttons. A large button labeled "three"
that spans the entire row. A button labeled "four" positioned in the bottom-left. Two labels "Serif" and "Monospaced" positioned in the bottom-
right.
GridBagDemo Class
package revision1.chapter25;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JTextField;
public class GridBagDemo extends JFrame{
private GridBagLayout container = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
public GridBagDemo() {
super("Grid Bag Layout");
setLayout(container);
JTextField textField = new JTextField("TextField");
String num[] = {"zero", "one", "two", "three", "four"};
JButton[] buttons = new JButton[num.length];
for (int i = 0; i < buttons.length; i++)
buttons[i] = new JButton(num[i]);
String metals[] = {"Copper", "Iron", "Aluminium"};
JComboBox comboBox = new JComboBox(metals);
String font[] = {"Serif", "Monospaced"};
JList list = new JList(font);
constraints.weightx = 1;
constraints.weighty = 1;
constraints.fill = GridBagConstraints.BOTH;
constraints.gridwidth = GridBagConstraints.REMAINDER;
addComponent(textField);
constraints.gridwidth = 1;
addComponent(buttons[0]);
constraints.gridwidth = GridBagConstraints.RELATIVE;
addComponent(buttons[1]);
constraints.gridwidth = GridBagConstraints.REMAINDER;
addComponent(buttons[2]);
constraints.weighty = 0;
constraints.gridwidth = GridBagConstraints.REMAINDER;
addComponent(comboBox);
constraints.weighty = 1;
constraints.gridwidth = GridBagConstraints.REMAINDER;
addComponent(buttons[3]);
constraints.gridwidth = GridBagConstraints.RELATIVE;
addComponent(buttons[4]);
constraints.gridwidth = GridBagConstraints.REMAINDER;
addComponent(list);
}
private void addComponent(Component component) {
container.setConstraints(component, constraints);
add(component);
}
public static void main(String[] args) {
GridBagDemo test = new GridBagDemo();
test.setVisible(true);
test.setSize(300, 200);
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Chapter 28 30 marks
Create an Author table of Book database using the following information.
Write a java program called DispalyAuthor that include only DisplayAuthor() method to show Author table of Book database.
Develop a Java database application that interacts with a Books Database. The application should allow users to:
1. Add a new author by entering their first name and last name.
2. Edit an existing author's information based on their AuthorID.
3. Exit the application when the user chooses the exit option.
The program should include Establishes a connection to a MySQL and ask user which option you should and also provide method for add new
author and edit author information based on AuthorID. Test add condition and edit condition..
CREATE TABLE Author(
AuthorID SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
FirstName VARCHAR(30) NOT NULL,
LastName VARCHAR(30) NOT NULL,
PRIMARY KEY(AuthorID)
);
INSERT INTO Author(FirstName, LastName) VALUES
("Paul", "Deitel"),
("Harvey", "Deitel"),
("Abbey", "Deitel"),
("Michael", "Morgano"),
("Eric", "Kern");
DisplayAuthor class
package revision1.chapter28;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
public class DisplayAuthor {
public static void displayAuthor() {
Connection connection = null;
Statement statement = null;
ResultSet resultset = null;
final String URL = "jdbc:mysql://localhost:3306/books";
final String USER = "root";
final String PASSWORD = "";
try {
connection = DriverManager.getConnection(URL, USER, PASSWORD);
statement = connection.createStatement();
resultset = statement.executeQuery("SELECT * FROM Author");
ResultSetMetaData metaData = resultset.getMetaData();
int numberOfColumns = metaData.getColumnCount();
System.out.println("Authors Table of Books Database\n");
for (int i = 1; i <= numberOfColumns; i++)
System.out.printf("%-8s\t", metaData.getColumnName(i));
System.out.println();
while(resultset.next()) {
for (int i = 1; i <= numberOfColumns; i++)
System.out.printf("%-8s\t", resultset.getObject(i));
System.out.println();
}
} catch (SQLException s) {
s.printStackTrace();
}
finally {
try {
resultset.close();
statement.close();
connection.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
BooksDatabaseApp class
package revision1.chapter28;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
public class BooksDatabaseApp {
private static final String URL = "jdbc:mysql://localhost:3306/books";
private static final String USER = "root";
private static final String PASSWORD = "";
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int choice;
try(Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {
System.out.println("Connected to the database.\n");
DisplayAuthor display = new DisplayAuthor();
display.displayAuthor();
while (true) {
System.out.println("\nChoose an operation:");
System.out.println("1. Add a new author");
System.out.println("2. Edit an author's information");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");
choice = input.nextInt();
switch (choice) {
case 1:
addNewAuthor(conn, input);
break;
case 2:
editAuthor(conn, input);
break;
case 3:
System.out.println("Exiting program");
return;
default:
System.out.println("Invalid choice, try again");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void addNewAuthor(Connection conn, Scanner input) throws SQLException {
input.nextLine();
System.out.print("Enter author's first name: ");
String fname = input.nextLine();
System.out.print("Enter author's last name: ");
String lname = input.nextLine();
String query = "INSERT INTO Author(FirstName, LastName) VALUES(?, ?)";
try(PreparedStatement stmt = conn.prepareStatement(query)){
stmt.setString(1, fname);
stmt.setString(2, lname);
stmt.executeUpdate();
System.out.println("Author added successfully\n");
}
DisplayAuthor display = new DisplayAuthor();
display.displayAuthor();
}
private static void editAuthor(Connection conn, Scanner input) throws SQLException {
System.out.print("Enter an AuthorID to edit: ");
int authorID = input.nextInt();
input.nextLine();
System.out.print("Enter author's first name: ");
String fname = input.nextLine();
System.out.print("Enter author's last name: ");
String lname = input.nextLine();
String query = "UPDATE Author SET FirstName = ?, LastName = ? WHERE AuthorID = ?";
try(PreparedStatement stmt = conn.prepareStatement(query)){
stmt.setString(1, fname);
stmt.setString(2, lname);
stmt.setInt(3, authorID);
int rowsUpdated = stmt.executeUpdate();
if(rowsUpdated > 0)
System.out.println("Author updated successfully\n");
else
System.out.println("No author found with the given ID");
}
DisplayAuthor display = new DisplayAuthor();
display.displayAuthor();
}
}