0% found this document useful (0 votes)
301 views41 pages

лаба 5

This document appears to be a laboratory work report for a course on Java Foundations and Java Programming from Saint Petersburg Polytechnic University. The report details the completion of 3 assignments involving exception handling, creating custom exception classes, and demonstrating different types of invariants in Java code. Code snippets are provided for an abstract bank account class and subclasses modeling different account types to complete one of the assignments.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
301 views41 pages

лаба 5

This document appears to be a laboratory work report for a course on Java Foundations and Java Programming from Saint Petersburg Polytechnic University. The report details the completion of 3 assignments involving exception handling, creating custom exception classes, and demonstrating different types of invariants in Java code. Code snippets are provided for an abstract bank account class and subclasses modeling different account types to complete one of the assignments.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 41

Санкт-Петербургский политехнический университет Петра Великого

Институт компьютерных наук и технологий


Высшая школа киберфизических систем и управления

ЛАБОРАТОРНАЯ РАБОТА №5
по дисциплине «Курсы Java Foundations и Java Programming»

Выполнил
студент
гр. 3530902/70201 _____________________ Медведева А.А.
подпись, дата

Проверил
_____________________ Нестеров С.А.
подпись, дата

Санкт-Петербург
2020
Выполнение задания
Задание 1

Решение:
1. try-with-resources
2. invariant class
3. Conditional statements 
4. try and catch block
5. Internal Invariants
6. Control Flow Invariants
7. Multi-Catch Statement
8. Finally Clause
9. Method-declared exceptions (throws)
Задание 2
1. You have included exception handling for the create button in the
JavaBank application. Do the same for the make transaction button.
2. Create an exception class called “myException” that accepts a String
message as a parameter in its constructor and passes the message to the super class
to be printed out when an error message is thrown.
3. Update all of the catch(Exception e)statements to create a MyException
object named newExc that sends the message "An unhandled error occurred!!" to
the console .
4. Create a block of code that utilizes all three types of invariants and asserts
their values.
Результат работы:

Задание 3
Результат работы:

Код программы:
public abstract class AbstractBankAccount {

//Instance Fields
public final String BANK= "JavaBank";
protected String accountName;
protected int accountNum;
protected int balance;

public abstract void deposit(int amt);

public AbstractBankAccount(String name, int num, int amt)


{
accountName=name;
accountNum=num;
balance=amt;
}//end constructor method

public String getBankName()


{
return InterfaceBankAccount.BANK;
}//end method getBankName

public String getaccountname ( ) {

return accountName;
}

public void setaccountname(String name) {

accountName = name;
}
public int getaccountnum ( ) {

return accountNum;
}

public void setaccountnum(int num)


{
accountNum = num;
}

public int getBalance() {


return balance;
}

public void setbalance(int num)


{
balance = num;
}

public void withdraw(int amt)


{
balance=balance-amt;
}

public String toString()


{
return "\nBank Name : " + getBankName() + "\nAccount Holder : "
+ accountName + "\nAccount Number : "
+ accountNum + "\nAccount balance: " + balance+"\n";
}//end method toString
}//end class AbstractBankAccount

public class Account extends AbstractBankAccount {

private AccountType type;


AccountType account = AccountType.DEPOSIT;

Account(String name, int num, int amt, AccountType type)


{
super(name, num, (amt + calculateInitialBonusValue(amt)));
this.type = type;
}//end constructor method

// class variables
private int bonusValue;

public void deposit(int amt)


{
if(amt>100) balance=balance+(amt + (int)(bonusValue * 0.1));
else balance=balance+amt; //endif
}//end method deposit

//print method
public void print()
{
System.out.println("\nBank Name : " + getBankName() + "\nAccount
Holder : " + accountName + "\nAccount Number : " + accountNum + "\nAccount balance: "
+ balance);
//System.out.println("Type: " + account.name() +"\nCode: " +
account.getCode() +"\nRate: " + account.getRate());
}//end method print

public String toString()


{
return "\nAccount Type : " + this.type + super.toString();

}//end method toString

private static int calculateInitialBonusValue(int amt)


{
if(amt >= 1 && amt <= 100) return 10;
else if(amt <= 300) return 20;
else return 30; //endif
}//end method calculateInitialBonusValue
}
public enum AccountType
{
CURRENT("CU", 1.0),
SAVINGS("SA", 2.0),
DEPOSIT("DP", 0.0),
CREDIT("CR", 3.0);

private String code;


private double rate;

private AccountType(String code, double rate)


{
this.code = code;
this.rate = rate;
}

public String getCode()


{
return code;
}//end method getCode

public double getRate()


{
return rate;
}//end method getRate
}//end enum AccountType

public class CreditAccount extends AbstractBankAccount{

int creditLimit;

//default constructor for CreditAccount


//overloaded constructor for CreditAccount
CreditAccount(String name, int num, int amt)
{
super(name,num,amt);
this.creditLimit=calculateCreditLimit(amt);
}//end constructor method
CreditAccount(String name, int num,int amt,int credit)
{
super(name,num,amt);
this.creditLimit=credit;

private static int calculateCreditLimit(int amt)


{
if(amt>1 && amt<=2000) return 100;
else if(amt<=4000) return 200;
else return 300; //endif
}//end method calculateCreditLimit

//modifier to set the account creditlimit


public void setcreditlimit(int num)
{
creditLimit = num;
}
//accessor to get the account creditlimit
public int getcreditlimit ( ) {

return creditLimit;
}
//print method
public void print() {
System.out.println("\nBank Name : " + getBankName()
+ "\nAccount Holder : " + accountName
+ "\nAccount Number : " + accountNum
+ "\nAccount balance: " + balance
+ "\nCredit Limit : " + creditLimit); ;
}
@Override
public void deposit(int amt)
{
balance=balance+amt;
}//end method deposit

public String toString()


{
return super.toString() + "\nCredit Limit : " + creditLimit;
}//end method toString
}
abstract interface InterfaceBankAccount
{
public final String BANK= "JavaBank";

public void deposit(int amt);


public void withdraw(int amt);
public int getBalance();
public String getBankName();

}//end interface InterfaceBankAccount


import java.awt.*;
//java -enableassertions JavaBank.java
import java.awt.event.*;
import java.util.InputMismatchException;

import javax.swing.*;
import javax.swing.border.*;

public class JavaBank extends JFrame {

private static final long serialVersionUID = 1L;


// Make these variables publicly available
public String Name;
public int Accountnum;
public int Balance;

// JPanel for user inputs


private JPanel inputDetailJPanel;

// JLabel and JTextField for account name


private JLabel NameJLabel;
private JTextField NameJTextField;

// JLabel and JTextField for account number


private JLabel AccountnumJLabel;
private JTextField AccountnumJTextField;

// JLabel and JTextField for balance


private JLabel BalanceJLabel;
private JTextField BalanceJTextField;

// JLabel and JTextField for withdraw


private JLabel DepositJLabel;
private JTextField DepositJTextField;

// JLabel and JTextField for Withdraw


private JLabel WithdrawJLabel;
private JTextField WithdrawJTextField;

// JButton to create account


private JButton CreateAccountJButton;

// JButton to delete account


private JButton DeleteAccountJButton;

// JButton to make transaction


private JButton TransactionJButton;

// JButton to display account


private JButton DisplayJButton;

// JLabel and JTextArea to display account details


private JLabel displayJLabel;
private static JTextArea displayJTextArea;

//combo box to display the account types.


private JComboBox<AccountType> accountTypes;
private AccountType actType = AccountType.SAVINGS;
// constants
//public final static Maximum Accounts that can be created;
public final static int MaxAccounts = 10;

// one-dimensional array to store Account names as Empty or Used


static String AccountNames[] = new String[MaxAccounts];

// two-dimensional array to store Account details

static AbstractBankAccount myAccounts[] = new AbstractBankAccount[MaxAccounts];


//создаем массив, элементами которого являются объекты абстрактного класса, в данном
случае объекты класса аккаунт

static int noAccounts = 0;

// constructor

public JavaBank() {
for (int i=0; i <10; i++) {
AccountNames[i] = "EMPTY";
//System.out.println(AccountNames[i]);

}
createUserInterface();
}

// create and position GUI components; register event handlers


private void createUserInterface() {
// get content pane for attaching GUI components
Container contentPane = getContentPane();

// enable explicit positioning of GUI components


contentPane.setLayout(null);

// set up inputDetailJPanel
inputDetailJPanel = new JPanel();
inputDetailJPanel.setBounds(16, 16, 208, 280);
inputDetailJPanel.setBorder(new TitledBorder("Input Details"));
inputDetailJPanel.setLayout(null);
contentPane.add(inputDetailJPanel);

// set up NameJLabel
NameJLabel = new JLabel();
NameJLabel.setBounds(8, 32, 90, 23);
NameJLabel.setText("Name:");
inputDetailJPanel.add(NameJLabel);

// set up NameJTextField
NameJTextField = new JTextField();
NameJTextField.setBounds(112, 32, 80, 21);
NameJTextField.setHorizontalAlignment(JTextField.RIGHT);
inputDetailJPanel.add(NameJTextField);
// set up AccountnumJLabel
AccountnumJLabel = new JLabel();
AccountnumJLabel.setBounds(8, 56, 100, 23);
AccountnumJLabel.setText("Account Number:");
inputDetailJPanel.add(AccountnumJLabel);

// set up AccountnumTextField
AccountnumJTextField = new JTextField();
AccountnumJTextField.setBounds(112, 56, 80, 21);
AccountnumJTextField.setHorizontalAlignment(JTextField.RIGHT);
inputDetailJPanel.add(AccountnumJTextField);

// set up BalanceJLabel
BalanceJLabel = new JLabel();
BalanceJLabel.setBounds(8, 80, 60, 23);
BalanceJLabel.setText("Balance:");
inputDetailJPanel.add(BalanceJLabel);

// set up BalanceTextField
BalanceJTextField = new JTextField();
BalanceJTextField.setBounds(112, 80, 80, 21);
BalanceJTextField.setHorizontalAlignment(JTextField.RIGHT);
inputDetailJPanel.add(BalanceJTextField);

// set up DepositJLabel
DepositJLabel = new JLabel();
DepositJLabel.setBounds(8, 104, 80, 23);
DepositJLabel.setText("Deposit:");
inputDetailJPanel.add(DepositJLabel);

// set up DepositJTextField
DepositJTextField = new JTextField();
DepositJTextField.setBounds(112, 104, 80, 21);
DepositJTextField.setHorizontalAlignment(JTextField.RIGHT);
inputDetailJPanel.add(DepositJTextField);

// set up WithdrawJLabel
WithdrawJLabel = new JLabel();
WithdrawJLabel.setBounds(8, 128, 60, 23);
WithdrawJLabel.setText("Withdraw:");
inputDetailJPanel.add(WithdrawJLabel);

// set up WithdrawJTextField
WithdrawJTextField = new JTextField();
WithdrawJTextField.setBounds(112, 128, 80, 21);
WithdrawJTextField.setHorizontalAlignment(JTextField.RIGHT);
inputDetailJPanel.add(WithdrawJTextField);

// set up CreateAccountButton
CreateAccountJButton = new JButton();
CreateAccountJButton.setBounds(112, 152, 80, 24);
CreateAccountJButton.setText("Create");
inputDetailJPanel.add(CreateAccountJButton);
CreateAccountJButton.addActionListener(

new ActionListener() {
// event handler called when CreateAccountJButton
// is clicked
public void actionPerformed(ActionEvent event) {
CreateAccountJButtonActionPerformed(event);
}

); // end call to addActionListener

// set up DeleteAccountButton
DeleteAccountJButton = new JButton();
DeleteAccountJButton.setBounds(16, 152, 80, 24);
DeleteAccountJButton.setText("Delete");
inputDetailJPanel.add(DeleteAccountJButton);
DeleteAccountJButton.addActionListener(

new ActionListener() // anonymous inner class


{
// event handler called when DeleteAccountJButton
// is clicked
public void actionPerformed(ActionEvent event) {
DeleteAccountJButtonActionPerformed(event);

); // end call to addActionListener

// set up TransactionJButton
TransactionJButton = new JButton();
TransactionJButton.setBounds(16, 180, 176, 24);
TransactionJButton.setText("Make Transaction");
inputDetailJPanel.add(TransactionJButton);
TransactionJButton.addActionListener(

new ActionListener() // anonymous inner class


{
// event handler called when TransactionJButton
// is clicked
public void actionPerformed(ActionEvent event) {
TransactionJButtonActionPerformed(event);
}

} // end anonymous inner class

); // end call to addActionListener

// set up DisplayJButton
DisplayJButton = new JButton();
DisplayJButton.setBounds(16, 208, 176, 24);
DisplayJButton.setText("Display Accounts");
inputDetailJPanel.add(DisplayJButton);
DisplayJButton.addActionListener(

new ActionListener() // anonymous inner class


{
// event handler called when TransactionJButton
// is clicked
public void actionPerformed(ActionEvent event) {
DisplayJButtonActionPerformed(event);
}

} // end anonymous inner class

); // end call to addActionListener

// set up accountTypes combo box


accountTypes = new JComboBox<AccountType>(AccountType.values());
accountTypes.setBounds(16, 238, 176, 24);
inputDetailJPanel.add(accountTypes);
accountTypes.addActionListener(
new ActionListener() // anonymous inner class
{
// event handler called when TransactionJButton
// is clicked
public void actionPerformed(ActionEvent event)
{
//accountTypes = (JComboBox)event.getSource();
actType = (AccountType)accountTypes.getSelectedItem();
}//end method actionPerformed
}//end ActionListener
); // end call to addActionListener

// set up displayJLabel
displayJLabel = new JLabel();
displayJLabel.setBounds(240, 16, 150, 23);
displayJLabel.setText("Account Details:");
contentPane.add(displayJLabel);

// set up displayJTextArea
displayJTextArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(displayJTextArea);
scrollPane.setBounds(240,48,402,245);

scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
contentPane.add(scrollPane);
displayJTextArea.setText("Welcome to Java Bank - There are currently no
Accounts created");

// clear other JTextFields for new data


NameJTextField.setText(" ");
AccountnumJTextField.setText("0");
BalanceJTextField.setText("0");
DepositJTextField.setText("0");
WithdrawJTextField.setText("0");

// set properties of application's window


setTitle("Java Bank"); // set title bar string
setSize(670, 340); // set window size
setVisible(true); // display window

} // end method createUserInterface

private void CreateAccountJButtonActionPerformed(ActionEvent event) {


// System.out.println("Create Account Button Clicked");
displayJTextArea.setText("");

Name = "";

//Get Name from Text Field


Name = NameJTextField.getText();

try
{

if (AccountnumJTextField.getText() == "0")
{
Accountnum = 0;
}
else
{
Accountnum = Integer.parseInt(AccountnumJTextField.getText());
}//endif
if (BalanceJTextField.getText() == "0")
{
Balance = 0;
}
else
{
Balance = Integer.parseInt(BalanceJTextField.getText());
}//endif
}//endtry
catch(NumberFormatException | InputMismatchException e)
{
Name=("");
JOptionPane.showMessageDialog(null, "Incorrect numeric value
entered." );
}//end catch
catch(Exception e) {
myException newExc = new myException("An unhandled error occurred!!");
//System.out.println(e);
}//end catch
finally {

assert ( Balance >= 0 ): "Неположительный баланс";

// clear the JTextFields for new data


NameJTextField.setText(" ");
AccountnumJTextField.setText("0");
BalanceJTextField.setText("0");
DepositJTextField.setText("0");
WithdrawJTextField.setText("0");
}//end finally

if ((noAccounts <= 9) & (Name != "") & (Accountnum != 0))


{
if(actType.equals(AccountType.CREDIT))
{
myAccounts[noAccounts] = new
CreditAccount(Name,Accountnum,Balance);
actType = AccountType.SAVINGS;
AccountNames[noAccounts] = "USED";
}
else
{
myAccounts[noAccounts] = new Account(Name,Accountnum,Balance,
actType);
AccountNames[noAccounts] = "USED";
}//endif

displayAccountDetails(myAccounts[noAccounts]);
noAccounts ++;
System.out.println(noAccounts);
}
else
{
displayJTextArea.setText("Both the Name field and Account Number must be
completed");
}//endif

if (noAccounts == 10) {
// Once account 10 is created. All accounts full.
displayJTextArea.setText("All Accounts Full!");
}
}

private void DeleteAccountJButtonActionPerformed(ActionEvent event) {

displayJTextArea.setText("Oops this isnt coded in this version!");


//Name = NameJTextField.getText();
//System.out.println("Delete Account: " + Name);

// Enter code to delete here

// clear JTextFields for new data

NameJTextField.setText(" ");
AccountnumJTextField.setText("0");
BalanceJTextField.setText("0");
DepositJTextField.setText("0");
WithdrawJTextField.setText("0");

private void TransactionJButtonActionPerformed(ActionEvent event) {

displayJTextArea.setText("");

try
{
if (noAccounts == 0)
{
displayJTextArea.setText("No Accounts currently created");
}
else
{
int Accountnum =
Integer.parseInt(AccountnumJTextField.getText());
int Deposit = Integer.parseInt(DepositJTextField.getText());
int Withdraw = Integer.parseInt(WithdrawJTextField.getText());

for (int i=0; i<noAccounts; i++) {


if ((myAccounts[i].getaccountnum() == Accountnum) && (Deposit>0))
{
myAccounts[i].setbalance(myAccounts[i].getBalance()
+Deposit);
displayJTextArea.setText("Bank Name : " +
myAccounts[i].getBankName() +"\nAccount Holder : " + myAccounts[i].getaccountname() +
"\nAccount Number : " + myAccounts[i].getaccountnum() + "\nAccount balance: " +
myAccounts[i].getBalance());
}

if ((myAccounts[i].getaccountnum() == Accountnum) &&


(Withdraw>0)) {

myAccounts[i].setbalance(myAccounts[i].getBalance()-Withdraw);

displayJTextArea.setText(myAccounts[i].getaccountname() + " " +


myAccounts[i].getaccountnum() + " " + myAccounts[i].getBalance());
}
}//endif
}
}
catch(NumberFormatException | InputMismatchException e)
{
Name=("");
JOptionPane.showMessageDialog(null, "Incorrect numeric value
entered." );
}//end catch
catch(Exception e)
{
myException newExc = new myException("An unhandled error occurred!!");
//System.out.println(e);
}//end catch
finally {
// clear the JTextFields for new data
NameJTextField.setText(" ");
AccountnumJTextField.setText("0");
BalanceJTextField.setText("0");
DepositJTextField.setText("0");
WithdrawJTextField.setText("0");
}//end finally

private void DisplayJButtonActionPerformed(ActionEvent event) {

Name = NameJTextField.getText();
displayJTextArea.setText("");

if (noAccounts == 0) {
displayJTextArea.setText("No Accounts currently created");
}else {
for (int i=0; i<noAccounts; i++) //проверка на отрицательный баланс
{
assert (myAccounts[i].getBalance()>0):"Отрицательный баланс";
}

assert (noAccounts>=2): "Создано меньше 2 аккаунтов"; //проверка на количество


созданных аккаунтов

for(int i=0; i<noAccounts; i++) //проверка на зарезервированное имя


{
switch(myAccounts[i].getaccountname())
{
case "1":
assert false:"Зарезервировано"; break;
case "2":
assert false:"Зарезервировано"; break;
case "3":
assert false:"Зарезервировано"; break;
case "4":
assert false:"Зарезервировано"; break;
default: break;
}
}

for (int i=0; i<noAccounts; i++) {

displayAccountDetails(myAccounts[i]);
//displayJTextArea.append(myAccounts[i].getaccountname() + " " +
myAccounts[i].getaccountnum() + " " + myAccounts[i].getBalance() + "\n");
}
}
// clear other JTextFields for new data
NameJTextField.setText(" ");
AccountnumJTextField.setText("0");
BalanceJTextField.setText("0");
DepositJTextField.setText("0");
WithdrawJTextField.setText("0");

private void displayAccountDetails(AbstractBankAccount name)


{
displayJTextArea.setText(name.toString());
//"Bank Name : " + name.BANK + "\nAccount Holder : "
//+ name.accountName + "\nAccount Number : " +
name.accountNum + "\nAccount balance: " + name.balance);
}//end method displayAccountDetails

public static void main(String[] args) {


// Populate arrays with the word EMPTY
// so we can check to see if the values are empty later

JavaBank application = new JavaBank();


application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.util.*;

public class JavaBankArrayListDelete extends JFrame {

/**
*
*/
private static final long serialVersionUID = 1L;
// Make these variables publicly available
public String Name;
public int Accountnum;
public int Balance;

// JPanel for user inputs


private JPanel inputDetailJPanel;

// JLabel and JTextField for account name


private JLabel NameJLabel;
private JTextField NameJTextField;

// JLabel and JTextField for account number


private JLabel AccountnumJLabel;
private JTextField AccountnumJTextField;

// JLabel and JTextField for balance


private JLabel BalanceJLabel;
private JTextField BalanceJTextField;

// JLabel and JTextField for withdraw


private JLabel DepositJLabel;
private JTextField DepositJTextField;

// JLabel and JTextField for Withdraw


private JLabel WithdrawJLabel;
private JTextField WithdrawJTextField;

// JButton to create account


private JButton CreateAccountJButton;

// JButton to delete account


private JButton DeleteAccountJButton;

// JButton to make transaction


private JButton TransactionJButton;

// JButton to display account


private JButton DisplayJButton;

// JLabel and JTextArea to display account details


private JLabel displayJLabel;
private static JTextArea displayJTextArea;
// array to store Account details and an Arraylist
ArrayList<Account> Accounts = new ArrayList<Account>();

//static int noAccounts = 0;

// constructor

public JavaBankArrayListDelete() {
//create the interface and start the application
createUserInterface();
}

// create and position GUI components; register event handlers


private void createUserInterface() {
// get content pane for attaching GUI components
Container contentPane = getContentPane();

// enable explicit positioning of GUI components


contentPane.setLayout(null);

// set up inputDetailJPanel
inputDetailJPanel = new JPanel();
inputDetailJPanel.setBounds(16, 16, 208, 250);
inputDetailJPanel.setBorder(new TitledBorder("Input Details"));
inputDetailJPanel.setLayout(null);
contentPane.add(inputDetailJPanel);

// set up NameJLabel
NameJLabel = new JLabel();
NameJLabel.setBounds(8, 32, 90, 23);
NameJLabel.setText("Name:");
inputDetailJPanel.add(NameJLabel);

// set up NameJTextField
NameJTextField = new JTextField();
NameJTextField.setBounds(112, 32, 80, 21);
NameJTextField.setHorizontalAlignment(JTextField.RIGHT);
inputDetailJPanel.add(NameJTextField);

// set up AccountnumJLabel
AccountnumJLabel = new JLabel();
AccountnumJLabel.setBounds(8, 56, 100, 23);
AccountnumJLabel.setText("Account Number:");
inputDetailJPanel.add(AccountnumJLabel);

// set up AccountnumTextField
AccountnumJTextField = new JTextField();
AccountnumJTextField.setBounds(112, 56, 80, 21);
AccountnumJTextField.setHorizontalAlignment(JTextField.RIGHT);
inputDetailJPanel.add(AccountnumJTextField);

// set up BalanceJLabel
BalanceJLabel = new JLabel();
BalanceJLabel.setBounds(8, 80, 60, 23);
BalanceJLabel.setText("Balance:");
inputDetailJPanel.add(BalanceJLabel);

// set up BalanceTextField
BalanceJTextField = new JTextField();
BalanceJTextField.setBounds(112, 80, 80, 21);
BalanceJTextField.setHorizontalAlignment(JTextField.RIGHT);
inputDetailJPanel.add(BalanceJTextField);

// set up DepositJLabel
DepositJLabel = new JLabel();
DepositJLabel.setBounds(8, 104, 80, 23);
DepositJLabel.setText("Deposit:");
inputDetailJPanel.add(DepositJLabel);

// set up DepositJTextField
DepositJTextField = new JTextField();
DepositJTextField.setBounds(112, 104, 80, 21);
DepositJTextField.setHorizontalAlignment(JTextField.RIGHT);
inputDetailJPanel.add(DepositJTextField);

// set up WithdrawJLabel
WithdrawJLabel = new JLabel();
WithdrawJLabel.setBounds(8, 128, 60, 23);
WithdrawJLabel.setText("Withdraw:");
inputDetailJPanel.add(WithdrawJLabel);

// set up WithdrawJTextField
WithdrawJTextField = new JTextField();
WithdrawJTextField.setBounds(112, 128, 80, 21);
WithdrawJTextField.setHorizontalAlignment(JTextField.RIGHT);
inputDetailJPanel.add(WithdrawJTextField);

// set up CreateAccountButton
CreateAccountJButton = new JButton();
CreateAccountJButton.setBounds(112, 152, 80, 24);
CreateAccountJButton.setText("Create");
inputDetailJPanel.add(CreateAccountJButton);
CreateAccountJButton.addActionListener(

new ActionListener() {
// event handler called when CreateAccountJButton
// is clicked
public void actionPerformed(ActionEvent event) {
CreateAccountJButtonActionPerformed(event);
}

); // end call to addActionListener

// set up DeleteAccountButton
DeleteAccountJButton = new JButton();
DeleteAccountJButton.setBounds(16, 152, 80, 24);
DeleteAccountJButton.setText("Delete");
inputDetailJPanel.add(DeleteAccountJButton);
DeleteAccountJButton.addActionListener(

new ActionListener() // anonymous inner class


{
// event handler called when DeleteAccountJButton
// is clicked
public void actionPerformed(ActionEvent event) {
DeleteAccountJButtonActionPerformed(event);

); // end call to addActionListener

// set up TransactionJButton
TransactionJButton = new JButton();
TransactionJButton.setBounds(16, 180, 176, 24);
TransactionJButton.setText("Make Transaction");
inputDetailJPanel.add(TransactionJButton);
TransactionJButton.addActionListener(

new ActionListener() // anonymous inner class


{
// event handler called when TransactionJButton
// is clicked
public void actionPerformed(ActionEvent event) {
TransactionJButtonActionPerformed(event);
}

} // end anonymous inner class

); // end call to addActionListener

// set up DisplayJButton
DisplayJButton = new JButton();
DisplayJButton.setBounds(16, 208, 176, 24);
DisplayJButton.setText("Display Accounts");
inputDetailJPanel.add(DisplayJButton);
DisplayJButton.addActionListener(

new ActionListener() // anonymous inner class


{
// event handler called when TransactionJButton
// is clicked
public void actionPerformed(ActionEvent event) {
DisplayJButtonActionPerformed(event);
}

} // end anonymous inner class

); // end call to addActionListener

// set up displayJLabel
displayJLabel = new JLabel();
displayJLabel.setBounds(240, 16, 150, 23);
displayJLabel.setText("Account Details:");
contentPane.add(displayJLabel);

// set up displayJTextArea
displayJTextArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(displayJTextArea);
scrollPane.setBounds(240,48,402,184);

scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
contentPane.add(scrollPane);
displayJTextArea.setText("Welcome to Java Bank - There are currently no
Accounts created");

// clear other JTextFields for new data


NameJTextField.setText("");
AccountnumJTextField.setText("0");
BalanceJTextField.setText("0");
DepositJTextField.setText("0");
WithdrawJTextField.setText("0");

// set properties of application's window


setTitle("Java Bank"); // set title bar string
setSize(670, 308); // set window size
setVisible(true); // display window

} // end method createUserInterface

private void CreateAccountJButtonActionPerformed(ActionEvent event) {


// System.out.println("Create Account Button Clicked");

displayJTextArea.setText("");

Name = "";

//Get Name from Text Field


Name = NameJTextField.getText();

//Get Accountnum from Text Field and convert to int unless blank then set to 0
if (AccountnumJTextField.getText() == "0") {
Accountnum = 0;
}
else {
Accountnum = Integer.parseInt(AccountnumJTextField.getText());
}

//Get Balance from Text Field and convert to int unless blank then set to 0
if (BalanceJTextField.getText() == "0") {
Balance = 0;
}
else {
Balance = Integer.parseInt(BalanceJTextField.getText());
}
if ((Name != "") & (Accountnum != 0)) {
//add a new account to the list using the Account constructor
Accounts.add(new
Account(Name,Accountnum,Balance,AccountType.SAVINGS));
//Set a temp Account for display purposes
Account tempAccount = (Account)Accounts.get(Accounts.size()-1);
//Display tempAccount
displayJTextArea.setText(Accounts.size() + " " +
tempAccount.getaccountname() + " " + tempAccount.getaccountnum() + " " +
tempAccount.getBalance());

}
else {
displayJTextArea.setText("Both the Name field and Account Number
must be completed");
}

// clear other JTextFields for new data


NameJTextField.setText("");
AccountnumJTextField.setText("0");
BalanceJTextField.setText("0");
DepositJTextField.setText("0");
WithdrawJTextField.setText("0");

private void DeleteAccountJButtonActionPerformed(ActionEvent event) {

if (Accounts.size() == 0) {
displayJTextArea.setText("No Accounts currently created");
}else {

// get user input


int Accountnum = Integer.parseInt(AccountnumJTextField.getText());

for ( int i = 0; i < Accounts.size(); i++ )


{
// get the element
Account tempAccount = (Account)Accounts.get(i);
if ((tempAccount.accountNum == Accountnum)) {
Accounts.remove(i);
//break;
}

}
}
NameJTextField.setText("");
AccountnumJTextField.setText("0");
BalanceJTextField.setText("0");
DepositJTextField.setText("0");
WithdrawJTextField.setText("0");

}
private void TransactionJButtonActionPerformed(ActionEvent event) {

displayJTextArea.setText("");

if (Accounts.size() == 0) {
displayJTextArea.setText("No Accounts currently created");
}else {

// get user input


int Accountnum = Integer.parseInt(AccountnumJTextField.getText());
int Deposit = Integer.parseInt(DepositJTextField.getText());
int Withdraw = Integer.parseInt(WithdrawJTextField.getText());

for ( int i = 0; i < Accounts.size(); i++ )


{
// get the element and set to TempAccount
Account tempAccount = (Account)Accounts.get(i);
// if account number matches and deposit field has entry then deposit
in account
if ((tempAccount.accountNum == Accountnum) && (Deposit>0)) {
tempAccount.setbalance(tempAccount.getBalance()+Deposit);
Accounts.set(i, tempAccount);
displayJTextArea.setText(tempAccount.getaccountname() + " " +
tempAccount.getaccountnum() + " " + tempAccount.getBalance());

}
// if account number matches and withdrawal field has entry then
withdraw from account
if ((tempAccount.accountNum == Accountnum) && (Withdraw>0)) {

tempAccount.setbalance(tempAccount.getBalance()-Withdraw);
Accounts.set(i, tempAccount);
displayJTextArea.setText(tempAccount.getaccountname() + " " +
tempAccount.getaccountnum() + " " + tempAccount.getBalance());

}
}
}

// clear other JTextFields for new data


NameJTextField.setText("");
AccountnumJTextField.setText("0");
BalanceJTextField.setText("0");
DepositJTextField.setText("0");
WithdrawJTextField.setText("0");

private void DisplayJButtonActionPerformed(ActionEvent event) {

Name = NameJTextField.getText();
displayJTextArea.setText("");
if (Accounts.isEmpty()) {
displayJTextArea.setText("No Accounts currently created");
}else {
for (int i=0; i < Accounts.size(); i++) {
Account tempAccount = (Account)Accounts.get(i);
displayJTextArea.append(tempAccount.getaccountname() + " " +
tempAccount.getaccountnum() + " " + tempAccount.getBalance() + "\n");

}
}
// clear other JTextFields for new data
NameJTextField.setText("");
AccountnumJTextField.setText("0");
BalanceJTextField.setText("0");
DepositJTextField.setText("0");
WithdrawJTextField.setText("0");
}

public static void main(String[] args) {


// Populate arrays with the word EMPTY
// so we can check to see if the values are empty later

JavaBankArrayListDelete application = new JavaBankArrayListDelete();


application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.border.*;

import java.util.*;

public class JavaBankList extends JFrame {

/**
*
*/
private static final long serialVersionUID = 1L;
// Make these variables publicly available
public String Name;
public int Accountnum;
public int Balance;

// JPanel for user inputs


private JPanel inputDetailJPanel;

// JLabel and JTextField for account name


private JLabel NameJLabel;
private JTextField NameJTextField;
// JLabel and JTextField for account number
private JLabel AccountnumJLabel;
private JTextField AccountnumJTextField;

// JLabel and JTextField for balance


private JLabel BalanceJLabel;
private JTextField BalanceJTextField;

// JLabel and JTextField for withdraw


private JLabel DepositJLabel;
private JTextField DepositJTextField;

// JLabel and JTextField for Withdraw


private JLabel WithdrawJLabel;
private JTextField WithdrawJTextField;

// JButton to create account


private JButton CreateAccountJButton;

// JButton to delete account


private JButton DeleteAccountJButton;

// JButton to make transaction


private JButton TransactionJButton;

// JButton to display account


private JButton DisplayJButton;

// JLabel and JTextArea to display account details


private JLabel displayJLabel;
private static JTextArea displayJTextArea;

// array to store Account details and an Arraylist


ArrayList<Account> Accounts = new ArrayList<Account>();

//static int noAccounts = 0;

// constructor

public JavaBankList() {
//create the interface and start the application
createUserInterface();
}

// create and position GUI components; register event handlers


private void createUserInterface() {
// get content pane for attaching GUI components
Container contentPane = getContentPane();

// enable explicit positioning of GUI components


contentPane.setLayout(null);
// set up inputDetailJPanel
inputDetailJPanel = new JPanel();
inputDetailJPanel.setBounds(16, 16, 208, 250);
inputDetailJPanel.setBorder(new TitledBorder("Input Details"));
inputDetailJPanel.setLayout(null);
contentPane.add(inputDetailJPanel);

// set up NameJLabel
NameJLabel = new JLabel();
NameJLabel.setBounds(8, 32, 90, 23);
NameJLabel.setText("Name:");
inputDetailJPanel.add(NameJLabel);

// set up NameJTextField
NameJTextField = new JTextField();
NameJTextField.setBounds(112, 32, 80, 21);
NameJTextField.setHorizontalAlignment(JTextField.RIGHT);
inputDetailJPanel.add(NameJTextField);

// set up AccountnumJLabel
AccountnumJLabel = new JLabel();
AccountnumJLabel.setBounds(8, 56, 100, 23);
AccountnumJLabel.setText("Account Number:");
inputDetailJPanel.add(AccountnumJLabel);

// set up AccountnumTextField
AccountnumJTextField = new JTextField();
AccountnumJTextField.setBounds(112, 56, 80, 21);
AccountnumJTextField.setHorizontalAlignment(JTextField.RIGHT);
inputDetailJPanel.add(AccountnumJTextField);

// set up BalanceJLabel
BalanceJLabel = new JLabel();
BalanceJLabel.setBounds(8, 80, 60, 23);
BalanceJLabel.setText("Balance:");
inputDetailJPanel.add(BalanceJLabel);

// set up BalanceTextField
BalanceJTextField = new JTextField();
BalanceJTextField.setBounds(112, 80, 80, 21);
BalanceJTextField.setHorizontalAlignment(JTextField.RIGHT);
inputDetailJPanel.add(BalanceJTextField);

// set up DepositJLabel
DepositJLabel = new JLabel();
DepositJLabel.setBounds(8, 104, 80, 23);
DepositJLabel.setText("Deposit:");
inputDetailJPanel.add(DepositJLabel);

// set up DepositJTextField
DepositJTextField = new JTextField();
DepositJTextField.setBounds(112, 104, 80, 21);
DepositJTextField.setHorizontalAlignment(JTextField.RIGHT);
inputDetailJPanel.add(DepositJTextField);

// set up WithdrawJLabel
WithdrawJLabel = new JLabel();
WithdrawJLabel.setBounds(8, 128, 60, 23);
WithdrawJLabel.setText("Withdraw:");
inputDetailJPanel.add(WithdrawJLabel);

// set up WithdrawJTextField
WithdrawJTextField = new JTextField();
WithdrawJTextField.setBounds(112, 128, 80, 21);
WithdrawJTextField.setHorizontalAlignment(JTextField.RIGHT);
inputDetailJPanel.add(WithdrawJTextField);

// set up CreateAccountButton
CreateAccountJButton = new JButton();
CreateAccountJButton.setBounds(112, 152, 80, 24);
CreateAccountJButton.setText("Create");
inputDetailJPanel.add(CreateAccountJButton);
CreateAccountJButton.addActionListener(

new ActionListener() {
// event handler called when CreateAccountJButton
// is clicked
public void actionPerformed(ActionEvent event) {
CreateAccountJButtonActionPerformed(event);
}

); // end call to addActionListener

// set up DeleteAccountButton
DeleteAccountJButton = new JButton();
DeleteAccountJButton.setBounds(16, 152, 80, 24);
DeleteAccountJButton.setText("Delete");
inputDetailJPanel.add(DeleteAccountJButton);
DeleteAccountJButton.addActionListener(

new ActionListener() // anonymous inner class


{
// event handler called when DeleteAccountJButton
// is clicked
public void actionPerformed(ActionEvent event) {
DeleteAccountJButtonActionPerformed(event);

); // end call to addActionListener

// set up TransactionJButton
TransactionJButton = new JButton();
TransactionJButton.setBounds(16, 180, 176, 24);
TransactionJButton.setText("Make Transaction");
inputDetailJPanel.add(TransactionJButton);
TransactionJButton.addActionListener(

new ActionListener() // anonymous inner class


{
// event handler called when TransactionJButton
// is clicked
public void actionPerformed(ActionEvent event) {
TransactionJButtonActionPerformed(event);
}

} // end anonymous inner class

); // end call to addActionListener

// set up DisplayJButton
DisplayJButton = new JButton();
DisplayJButton.setBounds(16, 208, 176, 24);
DisplayJButton.setText("Display Accounts");
inputDetailJPanel.add(DisplayJButton);
DisplayJButton.addActionListener(

new ActionListener() // anonymous inner class


{
// event handler called when TransactionJButton
// is clicked
public void actionPerformed(ActionEvent event) {
DisplayJButtonActionPerformed(event);
}

} // end anonymous inner class

); // end call to addActionListener

// set up displayJLabel
displayJLabel = new JLabel();
displayJLabel.setBounds(240, 16, 150, 23);
displayJLabel.setText("Account Details:");
contentPane.add(displayJLabel);

// set up displayJTextArea
displayJTextArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(displayJTextArea);
scrollPane.setBounds(240,48,402,184);

scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
contentPane.add(scrollPane);
displayJTextArea.setText("Welcome to Java Bank - There are currently
no Accounts created");

// clear other JTextFields for new data


NameJTextField.setText("");
AccountnumJTextField.setText("0");
BalanceJTextField.setText("0");
DepositJTextField.setText("0");
WithdrawJTextField.setText("0");

// set properties of application's window


setTitle("Java Bank"); // set title bar string
setSize(670, 308); // set window size
setVisible(true); // display window
} // end method createUserInterface

private void CreateAccountJButtonActionPerformed(ActionEvent event) {


// System.out.println("Create Account Button Clicked");

displayJTextArea.setText("");

Name = "";

//Get Name from Text Field


Name = NameJTextField.getText();

//Get Accountnum from Text Field and convert to int unless blank then
set to 0
if (AccountnumJTextField.getText() == "0") {
Accountnum = 0;
}
else {
Accountnum = Integer.parseInt(AccountnumJTextField.getText());
}

//Get Balance from Text Field and convert to int unless blank then set
to 0
if (BalanceJTextField.getText() == "0") {
Balance = 0;
}
else {
Balance = Integer.parseInt(BalanceJTextField.getText());
}

if ((Name != "") & (Accountnum != 0)) {


//add a new account to the list using the Account constructor
Accounts.add(new
Account(Name,Accountnum,Balance,AccountType.SAVINGS));
//Set a temp Account for display purposes
Account tempAccount =
(Account)Accounts.get(Accounts.size()-1);
//Display tempAccount
displayJTextArea.setText(Accounts.size() + " " +
tempAccount.getaccountname() + " " + tempAccount.getaccountnum() + " " +
tempAccount.getBalance());

}
else {
displayJTextArea.setText("Both the Name field and Account
Number must be completed");
}

// clear other JTextFields for new data


NameJTextField.setText("");
AccountnumJTextField.setText("0");
BalanceJTextField.setText("0");
DepositJTextField.setText("0");
WithdrawJTextField.setText("0");

private void DeleteAccountJButtonActionPerformed(ActionEvent event) {

displayJTextArea.setText("Oops this isnt coded in this version!");


//Name = NameJTextField.getText();
//System.out.println("Delete Account: " + Name);

// Enter code to delete here

// clear JTextFields for new data

NameJTextField.setText(" ");
AccountnumJTextField.setText("0");
BalanceJTextField.setText("0");
DepositJTextField.setText("0");
WithdrawJTextField.setText("0");

private void TransactionJButtonActionPerformed(ActionEvent event) {

displayJTextArea.setText("");

if (Accounts.size() == 0) {
displayJTextArea.setText("No Accounts currently created");
}else {

// get user input


int Accountnum = Integer.parseInt(AccountnumJTextField.getText());
int Deposit = Integer.parseInt(DepositJTextField.getText());
int Withdraw = Integer.parseInt(WithdrawJTextField.getText());

for ( int i = 0; i < Accounts.size(); i++ )


{
// get the element and set to TempAccount
Account tempAccount = (Account)Accounts.get(i);
// if account number matches and deposit field has entry then
deposit in account
if ((tempAccount.accountNum == Accountnum) && (Deposit>0)) {
tempAccount.setbalance(tempAccount.getBalance()
+Deposit);
Accounts.set(i, tempAccount);
displayJTextArea.setText(tempAccount.getaccountname() +
" " + tempAccount.getaccountnum() + " " + tempAccount.getBalance());

}
// if account number matches and withdrawal field has entry then
withdraw from account
if ((tempAccount.accountNum == Accountnum) && (Withdraw>0)) {

tempAccount.setbalance(tempAccount.getBalance()-Withdraw);
Accounts.set(i, tempAccount);
displayJTextArea.setText(tempAccount.getaccountname() +
" " + tempAccount.getaccountnum() + " " + tempAccount.getBalance());

}
}
}

// clear other JTextFields for new data


NameJTextField.setText("");
AccountnumJTextField.setText("0");
BalanceJTextField.setText("0");
DepositJTextField.setText("0");
WithdrawJTextField.setText("0");

private void DisplayJButtonActionPerformed(ActionEvent event) {

Name = NameJTextField.getText();
displayJTextArea.setText("");

if (Accounts.isEmpty()) {
displayJTextArea.setText("No Accounts currently created");
}else {
for (int i=0; i < Accounts.size(); i++) {
Account tempAccount = (Account)Accounts.get(i);
displayJTextArea.append(tempAccount.getaccountname() + " " +
tempAccount.getaccountnum() + " " + tempAccount.getBalance() + "\n");

}
}
// clear other JTextFields for new data
NameJTextField.setText("");
AccountnumJTextField.setText("0");
BalanceJTextField.setText("0");
DepositJTextField.setText("0");
WithdrawJTextField.setText("0");
}

public static void main(String[] args) {


// Populate arrays with the word EMPTY
// so we can check to see if the values are empty later

JavaBankList application = new JavaBankList();


application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

public class myException extends Exception


{
public myException(String message)
{
super(message);
}
}

public class testBank {

public static void main(String[] args) {

// Instantiate 3 accounts
// Using constructor with values
Account a1 = new Account("Sanjay Gupta",11556,300, AccountType.SAVINGS);
Account a2 = new Account("He Xai",22338,500, AccountType.SAVINGS);
Account a3 = new Account("Ilya Mustafana",44559,1000, AccountType.SAVINGS);

// Print accounts
a1.print();
a2.print();
a3.print();
}
}

public class testCreditAccount {

public static void main(String[] args) {

// Instantiate 3 accounts
// Using constructor with values
Account a1 = new Account("Sanjay Gupta",11556,300, AccountType.SAVINGS);
Account a2 = new Account("He Xai",22338,500, AccountType.SAVINGS);
Account a3 = new Account("Ilya Mustafana",44559,1000,
AccountType.SAVINGS);

// Instantiate 2 credit accounts using constructor with


// values which will call constructor from super
CreditAccount c1 = new CreditAccount("A.N Other", 88776, 500);
CreditAccount c2 = new CreditAccount("Another",66778,1000,500);

//a1.print();
System.out.println(a1);
//a2.print();
System.out.println(a2);
//a3.print();
System.out.println(a3);
//c1.print();
System.out.println(c1);
//c2.print();
System.out.println(c2);
}
}

public class TestCustomerAccount {


public static void main(String[] args) {
// TODO Auto-generated method stub
AbstractBankAccount[] bankAccount = new AbstractBankAccount[5];
// Instantiate 2 credit accounts using constructor with
bankAccount[0] = new Account("Sanjay Gupta",11556,300,
AccountType.SAVINGS);
bankAccount[1] = new Account("He Xai",22338,500, AccountType.SAVINGS);
bankAccount[2] = new Account("Ilya Mustafana",44559,1000,
AccountType.SAVINGS);

// Instantiate 2 credit accounts using constructor with


bankAccount[3] = new CreditAccount("A.N Other", 88776, 500);
bankAccount[4] = new CreditAccount("Another",66778,1000,500);

showAllCustomerAccounts(bankAccount);
showAllAccounts(bankAccount);
showAllCreditAccounts(bankAccount);
}

public static void showAllCustomerAccounts(AbstractBankAccount[] bankAccount)


{
System.out.print("\nAll Customer Accounts******");

for(AbstractBankAccount act: bankAccount)


System.out.println(act); //endfor
}//end method showAllCustomerAccounts

public static void showAllAccounts(AbstractBankAccount[] bankAccount)


{
System.out.print("\nAll Account types******");

for(AbstractBankAccount act: bankAccount)


if (act instanceof Account)
System.out.println(act); //endif //endfor
}//end method getAllAccounts

public static void showAllCreditAccounts(AbstractBankAccount[] bankAccount)


{
System.out.print("\nAll Credit Account types******");

for(AbstractBankAccount act: bankAccount)


if (act instanceof CreditAccount)
System.out.println(act); //endif //endfor
}//end method getAllCreditAccounts
}

Задание 4
Результат работы:

Код программы:
package bikeproject;

public abstract class Bike implements BikeParts{

private String handleBars, frame, tyres, seatType;


private int NumGears;
private final String make;
public Bike(){
this.make = "Oracle Cycles";
}//end constructor

public Bike(String handleBars, String frame, String tyres, String seatType,


int numGears) {
this.handleBars = handleBars;
this.frame = frame;
this.tyres = tyres;
this.seatType = seatType;
NumGears = numGears;
this.make = "Oracle Cycles";
}//end constructor

public String toString()


{
return "\n" + this.make + "\n"
+ "This bike has " + this.handleBars + " handlebars on a "
+ this.frame + " frame with " + this.NumGears + " gears."
+ "\nIt has a " + this.seatType + " seat with " + this.tyres +
" tyres.";
}

public String getHandleBars()


{
return handleBars;
}
public void setHandleBars(String newValue)
{
this.handleBars = newValue;
}
public String getTyres()
{
return tyres;
}
public void setTyres(String newValue)
{
this.tyres = newValue;
}
public String getSeatType()
{
return seatType;
}
public void setSeatType(String newValue)
{
this.seatType = newValue;
}

}//end class Bike

package bikeproject;

public class BikeDriver {

public static void main(String[] args) {

RoadBike bike1 = new RoadBike();


RoadBike bike2 = new RoadBike("drop", "tourer", "semi-grip", "comfort",
14, 25, 18);
MountainBike bike3 = new MountainBike();

System.out.println(bike1);
System.out.println(bike2);
System.out.println(bike3);

bike1.setPostHeight(20);
System.out.println(bike1);

}//end method main

}//end class BikeDriver

package bikeproject;

public interface BikeParts {


//constant declaration
public final String MAKE = "Oracle Bikes";

//required methods after implementation


public String getHandleBars();
public void setHandleBars(String newValue);
public String getTyres();
public void setTyres(String newValue);
public String getSeatType();
public void setSeatType(String newValue);

}//end interface BikeParts


package bikeproject;

public enum BikeUses {


off_road,
track,
road,
downhill,
trail
}

package bikeproject;

public class MountainBike extends Bike implements MountainParts{

private String suspension, type;


private int frameSize;

public MountainBike()
{
this("Bull Horn", "Hardtail", "Maxxis", "dropper", 27, "RockShox XC32",
"Pro", 19);
}//end constructor

public MountainBike(String handleBars, String frame, String tyres, String


seatType, int numGears,
String suspension, String type, int frameSize) {
super(handleBars, frame, tyres, seatType, numGears);
this.suspension = suspension;
this.type = type;
this.frameSize = frameSize;
}//end constructor

public String toString()


{
return super.toString()+"\nThis mountain bike is a " + this.type + "
bike and has a " + this.suspension + " suspension and a frame size of "
+ this.frameSize + "inches."+"\nThis bike is best for
"+terrain;
}

public String getSuspension()


{
return suspension;
}
public String getType()
{
return type;
}
public void setSuspension(String suspension)
{
this.suspension=suspension;
}
public void setType(String type)
{
this.type = type;
}
}//end class MountainBike

package bikeproject;

public interface MountainParts {


//constant declaration
//public final String TERRAIN = "off road";
public final BikeUses terrain = BikeUses.off_road;

public String getSuspension();


public String getType();

public void setSuspension(String newValue);


public void setType(String newValue);

package bikeproject;

public class RoadBike extends Bike implements RoadParts{

private int tyreWidth, postHeight;

public RoadBike()
{
this("drop", "racing", "tread less", "razor", 19, 20, 22);
}//end constructor

public RoadBike(int postHeight)


{
this("drop", "racing", "tread less", "razor", 19, 20, postHeight);
}//end constructor

public RoadBike(String handleBars, String frame, String tyres, String


seatType, int numGears,
int tyreWidth, int postHeight) {
super(handleBars, frame, tyres, seatType, numGears);
this.tyreWidth = tyreWidth;
this.postHeight = postHeight;
}//end constructor

public String toString()


{
return super.toString()+"\nThis Roadbike bike has " + this.tyreWidth +
"mm tyres and a post height of " + this.postHeight + "."
+"\nThis bike is best for "+terrain;
}
public int getTyreWidth()
{
return tyreWidth;
}
public int getPostHeight()
{
return postHeight;
}
public void setTyreWidth(int tyreWidth)
{
this.tyreWidth = tyreWidth;
}
public void setPostHeight(int postHeight)
{
this.postHeight = postHeight;
}
}//end class RoadBike
package bikeproject;

public interface RoadParts {

//public final String TERRAIN = "track_racing";


public final BikeUses terrain = BikeUses.track;

int getTyreWidth();
int getPostHeight();
void setTyreWidth(int tyreWidth);
void setPostHeight(int postHeight);
}

Задание 5
Результат работы:

Код программы:
package cuboid;

public class Cuboid<T extends Number> { //мы можем создавать только числовые
параметры сторон
private T height; //высота
private T breadth; //ширина
private T length; //длина

public String toString() //метод, выводящий значения сторон


{
return "\nlength: "+this.length+"\nbreadth: "+this.breadth+"\nheight:
"+this.height;
}
public double getVolume() //выводит объем
{
return
(height.doubleValue()*breadth.doubleValue()*length.doubleValue());
}
public T getHeight() {
return height;
}
public void setHeight(T height) {
this.height = height;
}
public T getBreadth() {
return breadth;
}
public void setBreadth(T breadth) {
this.breadth = breadth;
}
public T getLength() {
return length;
}
public void setLength(T length) {
this.length = length;
}
}

package cuboid;

public class DriverClass {

public static void main(String[] args) {


// TODO Auto-generated method stub
Cuboid<Double> c1 = new Cuboid<Double>(); //создаем параллелепипеда с
сторонами типа double
Cuboid<Integer> c2 = new Cuboid<Integer>(); //создаем параллелепипеда с
сторонами типа int

c1.setLength(1.3); //задаем значение длины для 1 фигуры


c1.setBreadth(2.2); //задаем значение ширины для 1 фигуры
c1.setHeight(2.0); //задаем значение высоты для 1 фигуры
System.out.println(c1); //выводим значения фигуры
System.out.println(c1.getVolume()); //выводим ее объем

c2.setLength(1); //задаем значение длины для 2 фигуры


c2.setBreadth(2); //задаем значение ширины для 2 фигуры
c2.setHeight(3); //задаем значение высоты для 2 фигуры
System.out.println(c2); //выводим значения сторон фигуры
System.out.println(c2.getVolume()); //выводим ее объем
}
}

You might also like