Bsc/Beng/Hnd Computing (Year 1)

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 37

BSc/BEng/HND COMPUTING

(Year 1)

Problem Solving & Programming (Assignment 2: Java)


Due for Issue (week Wednesday 12th Date for Friday 12th July
commencing): June 2019 Submission: 2019 (23h59).
Agreed Date for late submission: Module Tutor: Gary Hill
Signed:
Student Name: Pankaj Kumar
Mandal
ID: 19436768
Assessment Feedback
Aspect (& weighting)

Exercises (Quality of Coding, Code Listing


Screen Shots) (90%):
Report Presentation (Format, Layout,
Grammar, Syntax, Spelling) (10%):
Specific aspects of the assignment that the marker likes: Specific aspects of the assignment that need
more work:

Tutor’s Signature: Date: Grade:

1
CSY1020: Problem Solving Programming
Assignment 2: Programming (Java) (50%)

Pankaj Kumar Mandal

19436768

BSc Computing

University of Northampton

Submission date:

2
Contents
1. Introduction…………………………………………………………………………………………….. 4
2. Exercises……………………………………………………………………………………………………5
3. Conclusion…………………………………………………………………………………………………36
4. References…………………………………………………………………………………………………..37

3
Introduction
The assignment for problem solving and programming with 50% weightage has been coded
entirely in Java. According to (Eck and Colleges, 2010), Java is a high-level programming
language which is based on Class, Object, Structure etc. Though, Java is not a pure object-
oriented language, as it contains primitive type and developed to have as limited execution
dependencies as possible (Larsen, 2001). Spring Tool Suite 3.99 was as an IDE and the system
on which the author coded these programs was running JDK version 1.8.0_211 (Loo, 2007). The
programming code includes the thorough concept of Object-oriented programming that
includes its major characteristics like Encapsulation, Polymorphism, Interfaces, Inheritance etc.
(Huntley et al., 2019). The programs illustrated below are either console-based or GUI-based
(Murrell, 2008). The code and implementation parts shed some more individual lights for each
exercise addressed.

4
Exercises
Exercise: 3.3: Draw an empty Tic Tac Toe (noughts and crosses) board.

Code:

/**
Exercise: Draw an empty Tic Tac Toe (noughts and crosses) board.
Filename: Exercise3_3.java
@author:
Course: BSc Computing
Module: CSY1020 Problem Solving & Programming
Tutor:
@version: 1.0
Date:
*/
public class Exercise3_3 {

public static void main(String[] args) {


for(int i=0; i<2;i++) {
System.out.println(" __|__|__");
}
System.out.println(" | | ");

}
}

Implementation: The above code draws a tic tac toe board using a for loop. It runs on
console.

Exercise: 3.4: Design a simple house and draw it.

Code:

/**
Exercise: Design a simple house and draw it.
Filename: Exercise3_4.java
@author:
Course: BSc Computing
Module: CSY1020 Problem Solving & Programming
Tutor:
@version: 1.0
Date:
*/
import java.awt.*;

import javax.swing.*;

@SuppressWarnings("serial")
public class Exercise3_4 extends JPanel{

5
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.WHITE);

g.setColor(Color.RED);
g.fillRect(150,200, 160, 100);

g.setColor(Color.GREEN);
g.fillRect(150,100, 160, 100);

g.setColor(Color.BLACK);
g.fillRect(150,0, 160, 100);

g.setColor(Color.BLUE);
g.fillRect(150, 300, 160, 100);

g.setColor(Color.YELLOW);
g.fillRect(215, 360, 20, 40);

for(int i=160; i<300; i+=40) {


for(int j=30; j<360; j+=40) {
g.setColor(Color.WHITE);
g.fillRect(i, j, 15, 15);
}
}

public static void main(String[] args) {


JFrame f = new JFrame("House");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Exercise3_4 e = new Exercise3_4();
f.add(e);
f.setSize(500, 500);
f.setVisible(true);
}

Implementation: The above code draws a house using 2D graphics in a J-Frame.

6
Exercise: 4.1: Write a program to compute the volume of a box, given its three dimensions.

Code:

/**
Exercise: Write a program to compute the volume of a box, given its three dimensions.
Filename: Exercise4_1.java
@author:
Course: BSc Computing
Module: CSY1020 Problem Solving & Programming
Tutor:
@version: 1.0
Date:
*/
import java.util.Scanner;

public class Exercise4_1 {

public static void main(String[] args) {


int x;
int y;
int z;

Scanner sc = new Scanner(System.in);

System.out.println("Enter the dimensions of the box: ");


System.out.println("Length= ");
x = sc.nextInt();
System.out.println("Breadth= ");
y = sc.nextInt();
System.out.println("Height= ");
z = sc.nextInt();
printVol(x, y, z);
sc.close();

public static void printVol(int a, int b, int c) {


int vol = a * b * c;
System.out.println("Volume of the box with given dimensions is: \n" +
vol);
}
}

Implementation: The above code takes three input from user for length breadth and
height of a box and displays its volume to the user. This is console-based.

Exercise: 4.3: Write a program that inputs three integer exam marks, which displays the
mean (average) mark as a double value. Check your answer with a calculator.

7
Code:

/**
Exercise:Write a program that inputs three integer exam marks, which displays the
mean
(average) mark as a double value. Check your answer with a calculator.
Filename: Exercise4_3.java
@author:
Course: BSc Computing
Module: CSY1020 Problem Solving & Programming
Tutor:
@version: 1.0
Date:
*/

import java.util.Scanner;

public class Exercise4_3 {


public static void main(String[] args) {
int a;
int b;
int c;

Scanner sc = new Scanner(System.in);

System.out.println("Enter exam marks: ");


System.out.println("Marks 1= ");
a = sc.nextInt();
System.out.println("Marks 2= ");
b = sc.nextInt();
System.out.println("Marks 3= ");
c = sc.nextInt();
printMean(a, b, c);
sc.close();

public static void printMean(int a, int b, int c) {


double mean = (a + b + c) / 3;
System.out.println("Average marks obtained is: \n" + mean);
}
}

Exercise: 5.3: write a method named displayEarnings with two integer parameters
representing an employee’s salary and the number of years they have worked. The method
should display their total earnings in a message dialog, assuming that they earned the same
amount every year. The program should obtain values via input dialogs prior to calling
displayEarnings.

Code:

/**
Exercise: write a method named displayEarnings with two integer parameters
representing an

8
employee’s salary and the number of years they have worked. The method should display
their total
earnings in a message dialog, assuming that they
earned the same amount every year. The program should obtain values via input dialogs
prior to
calling
displayEarnings.
Filename: Exercise5_3.java
@author:
Course: BSc Computing
Module: CSY1020 Problem Solving & Programming
Tutor:
@version: 1.0
Date:
*/

import javax.swing.JFrame;
import javax.swing.JOptionPane;

@SuppressWarnings("serial")
public class Exercise5_3 extends JFrame {

public static void main(String[] args) {

int salary = Integer.parseInt(JOptionPane.showInputDialog("Enter Salary:


"));
int years = Integer.parseInt(JOptionPane.showInputDialog("Enter Years:
"));
displayEarnings(salary, years);

public static void displayEarnings(int s, int y) {


int total = s * 12 * y;
JOptionPane.showMessageDialog(null, "Total Earnings= " +
Integer.toString(total));
}

Implementation: The above code takes two integer parameters, salary and years
respectively and displays the total earnings. All of this is implemented through the use of
JOptionPane.

Exercise 6. 2. Write a program which produces a random number between 200 and 400
each time a button is clicked. The program should display this number, and the sum and
average of all the numbers so far. As you click again and again, the average should
converge on 300. If it doesn't, we would suspect the random number generator - just as we
would be suspicious of a coin that came out heads 100 times in a row!

Code:

/**

9
Exercise: Write a program which produces a random number between 200 and 400 each
time
a button is clicked. The program should display this number, and the sum and average
of all the
numbers so far. As you click again and again, the average should converge on 300. If
it doesn't, we
would suspect the random number generator - just as we would be suspicious of a coin
that came
out heads 100 times in a row!
Filename: Exercise6_2.java
@author:
Course: BSc Computing
Module: CSY1020 Problem Solving & Programming
Tutor:
@version: 1.0
Date:
*/

import java.awt.EventQueue;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

@SuppressWarnings("serial")
public class Exercise6_2 extends JFrame {

private JPanel contentPane;


private JButton btnNewButton;
private JLabel number;
private JLabel sum;
private JLabel Sumval;
private JLabel Average;
private JLabel Averageval;
private int s = 0;
private int avg = 0;
private int count = 0;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Exercise6_2 frame = new Exercise6_2();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}

10
}
});
}

/**
* Create the frame.
*/
public Exercise6_2() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
contentPane.add(getBtnNewButton());
contentPane.add(number());
contentPane.add(sum());
contentPane.add(getSumval());
contentPane.add(getAverage());
contentPane.add(getAverageval());
}

public void randomNumbers() {


Random r = new Random();

count++;
int n = r.nextInt(200) + 200;

s += n;
avg = s / count;
number.setText(String.valueOf(n));
Sumval.setText(String.valueOf(s));
Averageval.setText(String.valueOf(avg));

private JButton getBtnNewButton() {


if (btnNewButton == null) {
btnNewButton = new JButton("Generate");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
randomNumbers();
}
});
btnNewButton.setBounds(58, 52, 89, 23);
}
return btnNewButton;
}

private JLabel number() {


if (number == null) {
number = new JLabel("");
number.setBounds(256, 56, 46, 14);
}
return number;

11
}

private JLabel sum() {


if (sum == null) {
sum = new JLabel("Sum: ");
sum.setBounds(101, 103, 46, 14);
}
return sum;
}

private JLabel getSumval() {


if (Sumval == null) {
Sumval = new JLabel("");
Sumval.setBounds(196, 103, 46, 14);
}
return Sumval;
}

private JLabel getAverage() {


if (Average == null) {
Average = new JLabel("Average:");
Average.setBounds(101, 140, 46, 14);
}
return Average;
}

private JLabel getAverageval() {


if (Averageval == null) {
Averageval = new JLabel("");
Averageval.setBounds(196, 140, 46, 14);
}
return Averageval;
}
}

Implementation: The above code was implemented by extending J Frame class. This
program can generate a random number between 200 and 400 with the click of a button.
Additionally, it also has two features; sum and average. The sum feature displays the total
value of all the generated numbers added together in a particular session, and the average
feature displays the average value of all the numbers generated during that particular
session.

Exercise 7.4 Betting A group of people are betting on the outcome of three throws of the
dice. A person bets $1 on predicting the outcome of the three throws. Write a program that
uses the random number method to simulate three throws of a die and displays the
winnings according to the following rules:
• All three throws are sixes: win $20;
• All three throws are the same (but not sixes): win $10;
• Any two of the three throws are the same: win $5.

Code:

/**

12
Exercise: Betting A group of people are betting on the outcome of three throws of the
dice. A
person bets $1 on predicting the outcome of the three throws. Write a program that
uses the
random number method to simulate three throws of a die and displays the winnings
according to the
following rules:
• all three throws are sixes: win $20;
• all three throws are the same (but not sixes): win $10;
• any two of the three throws are the same: win $5.
Filename: Exercise7_4.java
@author:
Course: BSc Computing
Module: CSY1020 Problem Solving & Programming
Tutor:
@version: 1.0
Date:
*/

import java.util.Random;

public class Exercise7_4 {

public static void main(String[] args) {

Random r = new Random();


int n1 = r.nextInt(6 - 1) + 1;
System.out.println("Roll 1: " + n1);
int n2 = r.nextInt(6 - 1) + 1;
System.out.println("Roll 1: " + n2);
int n3 = r.nextInt(6 - 1) + 1;
System.out.println("Roll 1: " + n3);

if (n1 == n2 && n2 == n3 && n3 == 6) {


System.out.println("Congratulations you won 20$.");
}

else if (n1 == n2 && n2 == n3) {


System.out.println("Congratulations you won 10$.");
}

else if (n1 == n2 || n2 == n3 || n3 == n1) {


System.out.println("Congratulations you won 5$.");
}

else {
System.out.println("Sorry, no luck this time. You lost 1$");
}

13
Implementation: This program uses Random class to generate 3 random numbers
between 1 and 6 (including them) and based on the results and the rules of the question
displays the winnings to the user.

Exercise: 8.1: Write a program that uses a loop to display the integer numbers 1 to 10
together with the cubes of each of their values.

Code:
/**
Exercise: Write a program that uses a loop to display the integer numbers 1 to 10
together with the cubes of each of their values.
Filename: Exercise8_1.java
@author:
Course: BSc Computing
Module: CSY1020 Problem Solving & Programming
Tutor:
@version: 1.0
Date:
*/

public class Exercise8_1 {

public static void main(String[] args) {

for (int i=1; i<11; i++) {


System.out.println(i+" - "+Math.pow(i, 3) );
}

}
}

Implementation: This code prints 10 consecutive numbers starting from 1, along with
their respective cubes. Math.pow() function was used to achieve the cubes. The results are
printed in the console.

Exercise 8.2: Random Numbers. Write a program to display 10 random numbers using a
loop. Use
the library class Random to obtain integer random numbers in the range 0 to 9. Display the
numbers in a text field.

Code:

/**
Exercise: Random Numbers. Write a program to display 10 random numbers using a loop.
Use the library class Random to obtain integer random numbers in the range 0 to 9.
Display the numbers in a text field.
Filename: Exercise8_2.java
@author:
Course: BSc Computing
Module: CSY1020 Problem Solving & Programming
Tutor:
@version: 1.0

14
Date:
*/

import java.awt.EventQueue;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;

@SuppressWarnings("serial")
public class Exercise8_2 extends JFrame {

private JPanel contentPane;


private static JTextArea textArea;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Exercise8_2 frame = new Exercise8_2();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});

/**
* Create the frame.
*/
public Exercise8_2() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 521, 383);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
contentPane.add(getTextArea());
}

public static int randomNumber() {


Random r = new Random();
int n = r.nextInt(9 - 0) + 0;
return n;
}

private JTextArea getTextArea() {


if (textArea == null) {

15
textArea = new JTextArea(String.valueOf(randomNumber()) + "\n\n"
+ String.valueOf(randomNumber()) + "\n\n"
+ String.valueOf(randomNumber()) + "\n\n" +
String.valueOf(randomNumber()) + "\n\n"
+ String.valueOf(randomNumber()) + "\n\n" +
String.valueOf(randomNumber()) + "\n\n"
+ String.valueOf(randomNumber()) + "\n\n" +
String.valueOf(randomNumber()) + "\n\n"
+ String.valueOf(randomNumber()) + "\n\n" +
String.valueOf(randomNumber()));
textArea.setBounds(61, 11, 336, 322);
textArea.setColumns(10);
}
return textArea;
}
}

Implementation: The above code uses the Random class to generate random numbers
between 0-9 and display them in a text field.

Exercise 9.3: Bank account Write a program that simulates a bank account. A button
allows a deposit to be made into the account. The amount is entered into a text field. A
second button allows a withdrawal to be made. The amount (the balance) and the state of
the account is continually displayed - it is either OK or overdrawn. Create a class named
Account to represent bank accounts. It has methods deposit, withdraw,
getCurrentBalance and setCurrentbalance.

Code:

/**
Exercise: Bank account Write a program that simulates a bank account. A button allows
a deposit to be
made into the account. The amount is entered into a text field. A second button
allows a withdrawal
to be made. The amount (the balance) and the state of the account is continually
displayed - it is
either OK or overdrawn. Create a class named Account to represent bank accounts. It
has methods
deposit, withdraw, getCurrentBalance and setCurrentbalance.
Filename: Exercise9_3.java
@author:
Course: BSc Computing
Module: CSY1020 Problem Solving & Programming
Tutor:
@version: 1.0
Date:
*/

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;

16
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

@SuppressWarnings("serial")
public class Exercise9_3 extends JFrame {

private JPanel contentPane;


private JButton btnWithdraw;
private JButton btnDeposit;
private JTextField withdrawAmt;
private JTextField depositAmt;
private JLabel lblNewLabel;
private JLabel lblCurrentbalence;
private JLabel lblStatus;
private JLabel lblAccountstatus;

Account a = new Account();

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Exercise9_3 frame = new Exercise9_3();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the frame.
*/
public Exercise9_3() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
contentPane.add(getBtnWithdraw());
contentPane.add(getBtnDeposit());
contentPane.add(getWithdrawAmt());
contentPane.add(getDepositAmt());
contentPane.add(getLblNewLabel());
contentPane.add(getLblCurrentbalence());
contentPane.add(getLblStatus());
contentPane.add(getLblAccountstatus());
}

17
private JButton getBtnWithdraw() {
if (btnWithdraw == null) {
btnWithdraw = new JButton("Withdraw");
btnWithdraw.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double amt = Double.valueOf(withdrawAmt.getText());
a.withdraw(amt);

lblCurrentbalence.setText(String.valueOf(a.getCurrentBalance()));
if (a.getCurrentBalance() > 0)
lblAccountstatus.setText("OK");
else
lblAccountstatus.setText("Overdrawn");
withdrawAmt.setText(null);
}
});
btnWithdraw.setBounds(205, 56, 89, 23);
}
return btnWithdraw;
}

private JButton getBtnDeposit() {


if (btnDeposit == null) {
btnDeposit = new JButton("Deposit");
btnDeposit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double amt = Double.valueOf(depositAmt.getText());
a.deposit(amt);

lblCurrentbalence.setText(String.valueOf(a.getCurrentBalance()));
if (a.getCurrentBalance() > 0)
lblAccountstatus.setText("OK");
else
lblAccountstatus.setText("Overdrawn");
depositAmt.setText(null);
}
});
btnDeposit.setBounds(205, 102, 89, 23);
}
return btnDeposit;
}

private JTextField getWithdrawAmt() {


if (withdrawAmt == null) {
withdrawAmt = new JTextField();
withdrawAmt.setBounds(39, 59, 86, 20);
withdrawAmt.setColumns(10);
}
return withdrawAmt;
}

private JTextField getDepositAmt() {


if (depositAmt == null) {
depositAmt = new JTextField();

18
depositAmt.setBounds(39, 103, 86, 20);
depositAmt.setColumns(10);
}
return depositAmt;
}

private JLabel getLblNewLabel() {


if (lblNewLabel == null) {
lblNewLabel = new JLabel("Balance: ");
lblNewLabel.setBounds(60, 168, 65, 14);
}
return lblNewLabel;
}

private JLabel getLblCurrentbalence() {


if (lblCurrentbalence == null) {
lblCurrentbalence = new JLabel("0");
lblCurrentbalence.setBounds(205, 168, 89, 14);
}
return lblCurrentbalence;
}

private JLabel getLblStatus() {


if (lblStatus == null) {
lblStatus = new JLabel("Status: ");
lblStatus.setBounds(59, 204, 46, 14);
}
return lblStatus;
}

private JLabel getLblAccountstatus() {


if (lblAccountstatus == null) {
lblAccountstatus = new JLabel("OK");
lblAccountstatus.setBounds(205, 204, 118, 14);
}
return lblAccountstatus;
}
}

class Account {
private double currentBalance = 0;

public void deposit(double amt) {


setCurrentBalance(getCurrentBalance() + amt);
}

public void withdraw(double amt) {


setCurrentBalance(getCurrentBalance() - amt);
}

public double getCurrentBalance() {


return currentBalance;
}

public void setCurrentBalance(double currentBalance) {

19
this.currentBalance = currentBalance;
}

Implementation: The above code has a class named Account with the required methods
that are used in the GUI to withdraw, deposit, show current balance and show current
status of a bank account. Action listeners were added to the buttons to make them function
as was desired.

Exercise 9.4:
Scorekeeper Design and write a class that acts as a scorekeeper for a computer game. It
maintains a single integer, the score. It provides a method to initialize the score to zero, a
method to increase the score, a method to decrease the score, and a method to return the
score. Write a program to create a single object and use it. The current score is always on
display in a text field. Buttons are provided to increase, decrease and initialize the score by
an amount entered into a text field.

Code:

/**
Exercise: Scorekeeper Design and write a class that acts as a scorekeeper for a
computer game. It maintains
a single integer, the score. It provides a method to initialize the score to zero, a
method to increase
the score, a method to decrease the score, and a method to return the score. Write a
program to
create a single object and use it. The current score is always on display in a text
field. Buttons are
provided to increase, decrease and initialize the score by an amount entered into a
text field.
Filename: Exercise9_4.java
@author:
Course: BSc Computing
Module: CSY1020 Problem Solving & Programming
Tutor:
@version: 1.0
Date:
*/

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

@SuppressWarnings("serial")

20
public class Exercise9_4 extends JFrame {

private JPanel contentPane;


private JLabel lblCurrentScore;
private JLabel lblScore;
private JButton btnIncreaseBy;
private JButton btnDecreaseBy;
private JButton btnInitializeTo;
private JTextField txtInitialize;
private JTextField txtIncrease;
private JTextField txtDecrease;

ScoreKeeper s = new ScoreKeeper();


private JButton btnZero;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Exercise9_4 frame = new Exercise9_4();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the frame.
*/
public Exercise9_4() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
contentPane.add(getLblCurrentScore());
contentPane.add(getLblScore());
contentPane.add(getBtnIncreaseBy());
contentPane.add(getBtnDecreaseBy());
contentPane.add(getBtnInitializeTo());
contentPane.add(getTxtInitialize());
contentPane.add(getTxtIncrease());
contentPane.add(getTxtDecrease());
contentPane.add(getBtnZero());
}

private JLabel getLblCurrentScore() {


if (lblCurrentScore == null) {
lblCurrentScore = new JLabel("Current Score:");

21
lblCurrentScore.setBounds(29, 38, 84, 14);
}
return lblCurrentScore;
}

private JLabel getLblScore() {


if (lblScore == null) {
lblScore = new JLabel("0");
lblScore.setBounds(233, 38, 46, 14);
}
return lblScore;
}

private JButton getBtnIncreaseBy() {


if (btnIncreaseBy == null) {
btnIncreaseBy = new JButton("Increase by:");
btnIncreaseBy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int amt = Integer.valueOf(txtIncrease.getText());
s.increase(amt);
lblScore.setText(String.valueOf(s.getScore()));
txtIncrease.setText(null);
}
});
btnIncreaseBy.setBounds(29, 132, 119, 23);
}
return btnIncreaseBy;
}

private JButton getBtnDecreaseBy() {


if (btnDecreaseBy == null) {
btnDecreaseBy = new JButton("Decrease by:");
btnDecreaseBy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int amt = Integer.valueOf(txtDecrease.getText());
s.decrease(amt);
lblScore.setText(String.valueOf(s.getScore()));
txtDecrease.setText(null);
}
});
btnDecreaseBy.setBounds(29, 181, 119, 23);
}
return btnDecreaseBy;
}

private JButton getBtnInitializeTo() {


if (btnInitializeTo == null) {
btnInitializeTo = new JButton("Initialize to:");
btnInitializeTo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int amt = Integer.valueOf(txtInitialize.getText());
s.setScore(amt);
lblScore.setText(String.valueOf(s.getScore()));
txtInitialize.setText(null);
}

22
});
btnInitializeTo.setBounds(29, 79, 119, 23);
}
return btnInitializeTo;
}

private JTextField getTxtInitialize() {


if (txtInitialize == null) {
txtInitialize = new JTextField();
txtInitialize.setText("");
txtInitialize.setBounds(233, 80, 86, 20);
txtInitialize.setColumns(10);
}
return txtInitialize;
}

private JTextField getTxtIncrease() {


if (txtIncrease == null) {
txtIncrease = new JTextField();
txtIncrease.setText("");
txtIncrease.setBounds(233, 133, 86, 20);
txtIncrease.setColumns(10);
}
return txtIncrease;
}

private JTextField getTxtDecrease() {


if (txtDecrease == null) {
txtDecrease = new JTextField();
txtDecrease.setText("");
txtDecrease.setBounds(233, 182, 86, 20);
txtDecrease.setColumns(10);
}
return txtDecrease;
}

private JButton getBtnZero() {


if (btnZero == null) {
btnZero = new JButton("to 0");
btnZero.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
s.toZero();
lblScore.setText("0");
}
});
btnZero.setBounds(335, 79, 89, 23);
}
return btnZero;
}
}

class ScoreKeeper {
private int score;

public void toZero() {

23
setScore(0);
}

public void increase(int amt) {


setScore(getScore() + amt);
}

public void decrease(int amt) {


setScore(getScore() - amt);
}

public int getScore() {


return score;
}

public void setScore(int score) {


this.score = score;
}

Implementation: The above code has an integer that can be manipulated using buttons to
initialize, increase or decrease it to the desired value. This program also makes use of two
classes, one that maintains the score and another that runs the GUI. The user can input
numbers in the fields provided to manipulate the score as they desire.

Exercise 11.1: Cost of phone call. A phone call costs 10 cents per minute. Write a program
that inputs via text fields the duration of a phone call, expressed in hours, minutes and
seconds, and displays the cost of the phone call in cents, accurate to the nearest cent.

Code:

/**
Exercise: Cost of phone call. A phone call costs 10 cents per minute.
Write a program that inputs via text fields the duration of a phone call, expressed
in hours, minutes
and seconds, and displays the cost of the phone call in cents, accurate to the
nearest cent.
Filename: Exercise11_1.java
@author:
Course: BSc Computing
Module: CSY1020 Problem Solving & Programming
Tutor:
@version: 1.0
Date:
*/

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;

24
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

@SuppressWarnings("serial")
public class Exercise11_1 extends JFrame {

private JPanel contentPane;


private JLabel lblTimeOfCall;
private JLabel lblHours;
private JLabel lblMinutes;
private JLabel lblSeconds;
private JTextField txtHrs;
private JTextField txtMins;
private JTextField txtSecs;
private JButton btnCalculateCost;
private JLabel lblCallcost;
private JLabel lblChargeRate;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Exercise11_1 frame = new Exercise11_1();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the frame.
*/
public Exercise11_1() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
contentPane.add(getLblTimeOfCall());
contentPane.add(getLblHours());
contentPane.add(getLblMinutes());
contentPane.add(getLblSeconds());
contentPane.add(getTxtHrs());
contentPane.add(getTxtMins());
contentPane.add(getTxtSecs());
contentPane.add(getBtnCalculateCost());
contentPane.add(getLblCallcost());
contentPane.add(getLblChargeRate());

25
}

public int calculateCost() {


double totalmins = Double.valueOf(txtHrs.getText()) * 60 +
Double.valueOf(txtMins.getText())
+ Double.valueOf(txtSecs.getText()) / 60;
int cost = (int) (totalmins * 10);
return cost;
}

private JLabel getLblTimeOfCall() {


if (lblTimeOfCall == null) {
lblTimeOfCall = new JLabel("Time of Call -");
lblTimeOfCall.setBounds(10, 32, 100, 14);
}
return lblTimeOfCall;
}

private JLabel getLblHours() {


if (lblHours == null) {
lblHours = new JLabel("Hours:");
lblHours.setBounds(10, 74, 58, 14);
}
return lblHours;
}

private JLabel getLblMinutes() {


if (lblMinutes == null) {
lblMinutes = new JLabel("Minutes:");
lblMinutes.setBounds(10, 114, 58, 14);
}
return lblMinutes;
}

private JLabel getLblSeconds() {


if (lblSeconds == null) {
lblSeconds = new JLabel("Seconds:");
lblSeconds.setBounds(10, 159, 58, 14);
}
return lblSeconds;
}

private JTextField getTxtHrs() {


if (txtHrs == null) {
txtHrs = new JTextField();
txtHrs.setText("0");
txtHrs.setBounds(78, 74, 86, 20);
txtHrs.setColumns(10);
}
return txtHrs;
}

private JTextField getTxtMins() {


if (txtMins == null) {
txtMins = new JTextField();

26
txtMins.setText("0");
txtMins.setBounds(78, 114, 86, 20);
txtMins.setColumns(10);
}
return txtMins;
}

private JTextField getTxtSecs() {


if (txtSecs == null) {
txtSecs = new JTextField();
txtSecs.setText("0");
txtSecs.setBounds(78, 159, 86, 20);
txtSecs.setColumns(10);
}
return txtSecs;
}

private JButton getBtnCalculateCost() {


if (btnCalculateCost == null) {
btnCalculateCost = new JButton("Calculate Cost");
btnCalculateCost.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
lblCallcost.setText(String.valueOf(calculateCost())
+ " cents");
txtHrs.setText("0");
txtMins.setText("0");
txtSecs.setText("0");
}
});
btnCalculateCost.setBounds(49, 205, 118, 23);
}
return btnCalculateCost;
}

private JLabel getLblCallcost() {


if (lblCallcost == null) {
lblCallcost = new JLabel("0 cents");
lblCallcost.setBounds(260, 209, 118, 14);
}
return lblCallcost;
}

private JLabel getLblChargeRate() {


if (lblChargeRate == null) {
lblChargeRate = new JLabel("Charge rate= 10 cents per min");
lblChargeRate.setBounds(214, 114, 179, 14);
}
return lblChargeRate;
}
}

Implementation: The above code is also made in swing. The user can input time in three
formats, hours, minutes and seconds. A button is provided which calculates the total cost of
the call and displays it to the user.

27
Exercise 11.2: Measurement Conversion. Write a program to input a measurement
expressed in feet and inches via two text fields. When a button is clicked, convert the
measurement to centimeters and display it in a text field, correct to two decimal places.
There are 12 inches in a foot; 1 inch is 2.54 centimeters.

Code:
/**
Exercise: Measurement Conversion. Write a program to input a measurement expressed in
feet
and inches via two text fields. When a button is clicked, convert the measurement to
centimetres
and display it in a text field, correct to two decimal places. There are 12 inches in
a foot; 1 inch is
2.54 centimetres.
Filename: Exercise11_2.java
@author:
Course: BSc Computing
Module: CSY1020 Problem Solving & Programming
Tutor:
@version: 1.0
Date:
*/

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

@SuppressWarnings("serial")
public class Exercise11_2 extends JFrame {

private JPanel contentPane;


private JLabel lblInches;
private JLabel lblFeet;
private JTextField txtIn;
private JTextField txtFt;
private JButton btnConvert;
private JLabel lblIncm;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {

28
public void run() {
try {
Exercise11_2 frame = new Exercise11_2();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the frame.
*/
public Exercise11_2() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
contentPane.add(getLblInches());
contentPane.add(getLblFeet());
contentPane.add(getTxtIn());
contentPane.add(getTxtFt());
contentPane.add(getBtnConvert());
contentPane.add(getLblIncm());
}

public double convert() {


double result = Double.valueOf(txtFt.getText()) * 12 * 2.54 +
Double.valueOf(txtIn.getText()) * 2.54;

return result;

private JLabel getLblInches() {


if (lblInches == null) {
lblInches = new JLabel("Inches:");
lblInches.setBounds(51, 49, 46, 14);
}
return lblInches;
}

private JLabel getLblFeet() {


if (lblFeet == null) {
lblFeet = new JLabel("Feet:");
lblFeet.setBounds(51, 95, 46, 14);
}
return lblFeet;
}

private JTextField getTxtIn() {


if (txtIn == null) {

29
txtIn = new JTextField();
txtIn.setText("0");
txtIn.setBounds(141, 46, 86, 20);
txtIn.setColumns(10);
}
return txtIn;
}

private JTextField getTxtFt() {


if (txtFt == null) {
txtFt = new JTextField();
txtFt.setText("0");
txtFt.setBounds(141, 92, 86, 20);
txtFt.setColumns(10);
}
return txtFt;
}

private JButton getBtnConvert() {


if (btnConvert == null) {
btnConvert = new JButton("Convert");
btnConvert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double res = convert();
lblIncm.setText(String.valueOf(res) + " cm");
txtFt.setText("0");
txtIn.setText("0");

}
});
btnConvert.setBounds(51, 157, 89, 23);
}
return btnConvert;
}

private JLabel getLblIncm() {


if (lblIncm == null) {
lblIncm = new JLabel("0.00 cm");
lblIncm.setBounds(181, 161, 86, 14);
}
return lblIncm;
}
}

Implementation: The above program has two text boxes to take input from the user for
feet and inches. The convert button then converts this measurement to centimeters within a
precision of 2 decimal points. This result is then displayed to the user.

Exercise: 15.1: Write a program which inputs two strings from text fields, and which joins
them together. Show the resulting string in a text field.

Code:
/**

30
Exercise: Measurement Conversion. Write a program to input a measurement expressed in
feet
and inches via two text fields. When a button is clicked, convert the measurement to
centimetres
and display it in a text field, correct to two decimal places. There are 12 inches in
a foot; 1 inch is
2.54 centimetres.
Filename: Exercise11_2.java
@author:
Course: BSc Computing
Module: CSY1020 Problem Solving & Programming
Tutor:
@version: 1.0
Date:
*/

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

@SuppressWarnings("serial")
public class Exercise11_2 extends JFrame {

private JPanel contentPane;


private JLabel lblInches;
private JLabel lblFeet;
private JTextField txtIn;
private JTextField txtFt;
private JButton btnConvert;
private JLabel lblIncm;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Exercise11_2 frame = new Exercise11_2();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**

31
* Create the frame.
*/
public Exercise11_2() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
contentPane.add(getLblInches());
contentPane.add(getLblFeet());
contentPane.add(getTxtIn());
contentPane.add(getTxtFt());
contentPane.add(getBtnConvert());
contentPane.add(getLblIncm());
}

public double convert() {


double result = Double.valueOf(txtFt.getText()) * 12 * 2.54 +
Double.valueOf(txtIn.getText()) * 2.54;

return result;

private JLabel getLblInches() {


if (lblInches == null) {
lblInches = new JLabel("Inches:");
lblInches.setBounds(51, 49, 46, 14);
}
return lblInches;
}

private JLabel getLblFeet() {


if (lblFeet == null) {
lblFeet = new JLabel("Feet:");
lblFeet.setBounds(51, 95, 46, 14);
}
return lblFeet;
}

private JTextField getTxtIn() {


if (txtIn == null) {
txtIn = new JTextField();
txtIn.setText("0");
txtIn.setBounds(141, 46, 86, 20);
txtIn.setColumns(10);
}
return txtIn;
}

private JTextField getTxtFt() {


if (txtFt == null) {
txtFt = new JTextField();
txtFt.setText("0");

32
txtFt.setBounds(141, 92, 86, 20);
txtFt.setColumns(10);
}
return txtFt;
}

private JButton getBtnConvert() {


if (btnConvert == null) {
btnConvert = new JButton("Convert");
btnConvert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double res = convert();
lblIncm.setText(String.valueOf(res) + " cm");
txtFt.setText("0");
txtIn.setText("0");

}
});
btnConvert.setBounds(51, 157, 89, 23);
}
return btnConvert;
}

private JLabel getLblIncm() {


if (lblIncm == null) {
lblIncm = new JLabel("0.00 cm");
lblIncm.setBounds(181, 161, 86, 14);
}
return lblIncm;
}
}

Implementation: This program makes simple use of text boxes to get strings from the
user and when the user clicks join, the concatenated version of these strings is displayed.

Exercise: 15.2: Write a program which inputs one string and determines whether or not it is
a palindrome. A palindrome reads the same backwards and forwards, so "abba" is a
palindrome.

Code:
/**
Exercise: Write a program which inputs one string and determines whether or not it is
a palindrome. A palindrome reads the same backwards and forwards, so "abba" is a
palindrome.
Filename: Exercise15_2.java
@author:
Course: BSc Computing
Module: CSY1020 Problem Solving & Programming
Tutor:
@version: 1.0
Date:
*/

import java.awt.EventQueue;

33
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

@SuppressWarnings("serial")
public class Exercise15_2 extends JFrame {

private JPanel contentPane;


private JLabel lblInputString;
private JTextField txtInp;
private JButton btnCheckPalindrome;
private JLabel lblCheckres;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Exercise15_2 frame = new Exercise15_2();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the frame.
*/
public Exercise15_2() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
contentPane.add(getLblInputString());
contentPane.add(getTxtInp());
contentPane.add(getBtnCheckPalindrome());
contentPane.add(getLblCheckres());
}

private JLabel getLblInputString() {


if (lblInputString == null) {
lblInputString = new JLabel("Input String:");
lblInputString.setBounds(26, 44, 77, 14);

34
}
return lblInputString;
}

private JTextField getTxtInp() {


if (txtInp == null) {
txtInp = new JTextField();
txtInp.setText("");
txtInp.setBounds(36, 69, 365, 20);
txtInp.setColumns(10);
}
return txtInp;
}

private JButton getBtnCheckPalindrome() {


if (btnCheckPalindrome == null) {
btnCheckPalindrome = new JButton("Check Palindrome");
btnCheckPalindrome.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = txtInp.getText();
String p = "";
for (int i = s.length() - 1; i >= 0; i--) {
p = p + s.charAt(i);
}
if (s.equalsIgnoreCase(p))
lblCheckres.setText("The string is a
palindrome.");

else
lblCheckres.setText("The string is not a
palindrome.");
}
});
btnCheckPalindrome.setBounds(118, 113, 181, 23);
}
return btnCheckPalindrome;
}

private JLabel getLblCheckres() {


if (lblCheckres == null) {
lblCheckres = new JLabel("No string inserted yet!");
lblCheckres.setBounds(36, 165, 365, 14);
}
return lblCheckres;
}
}

Implementation: This program also makes use of text box to get input from the user and
uses a simple logic to check for palindrome and displays to the user after they click the
check button whether the input string is its palindrome.

35
Conclusion
This assignment was a result of extreme hard work on both coding as well as researching front
on the part of the author. Completing these exercises have certainly been challenging as well as
rewarding and the author thoroughly enjoyed most of the aspects related to this assignment.
Though all the exercises could not be addressed, regretfully due to time constraints, those that
have been addressed have been done in an original manner as possible.

References
Eck, D. J. and Colleges, W. S. (2010) ‘Introduction to Programming Using Java’, Environments.
Huntley, J. et al. (2019) ‘Introduction to Object-Oriented Programming’, in Game Programming
for Artists. doi: 10.1201/b22049-4.
Larsen, A. L. (2001) ‘Java programming’, ACM SIGSOFT Software Engineering Notes. doi:
10.1145/505894.505922.
Loo, A. W.-S. (2007) ‘Java Network Programming’, in Peer-to-Peer Computing. doi: 10.1007/978-
1-84628-747-3_7.
Murrell, P. (2008) ‘A GUI-Builder Approach to grid Graphics’, Study R.

*The forum sites present here have been used for concepts of Java programming; however, it is
less likely to have its influence on direct questions but it does reflect indirect references to
those solved similar problems.

36
37

You might also like