Account Interest Calculator: How to Pass Array Value to an Object? - java

I've reached a brick wall in a Java sample project been working on. My goal with this project is to calculate interest using user input to determine what kind of account is being used, and calculating based on each specific account type.
Right now I have created a factory method "public Account createAccount". I need it to accept the string parameter from the user prompt. To tell me if it is Checking, Savings or CD. Now here is where I run into trouble. I have to pass the user value for the "accttype" to a new object specific for each account type. My problem is I just don't know how to do this. Do I have to implement in the factory method? How can I pass these values? Thanks in advance
Account.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Account implements ActionListener {
JButton calculate;
private int period;
private int balance;
private int fbalance;
private int rate;
private int monthlyFee;
private String printstring;
#Override
public String toString() {
return String.format("Period: " + period + ", Balance: " + balance);
}
public int getPeriod() {
return period;
}
public void setPeriod(int period) {
this.period = period;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
public int getRate() {
return rate;
}
public void setRate(int rate) {
this.rate = rate;
}
public int getFbalance() {
return fbalance;
}
public void setFbalance(int fbalance) {
this.fbalance = fbalance;
}
public String getPrintstring() {
return printstring;
}
public void setPrintString(String printstring) {
this.printstring = printstring;
}
public void calculate() {
for ( int i = 0; i<period; i++)
{
fbalance = balance + balance * rate - monthlyFee;
}
}
public void actionPerformed(ActionEvent e) {
calculate();
}
}
Banker.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Banker {
// Array for type of bank account
private static void createAndShowGUI() {
// Declare strings for period, balance, rate
String period;
String balance;
String rate;
// Prompt for account type
String[] accttype = { "Checking", "Savings", "CD" }; // Array of bank acct types
String input = (String) JOptionPane.showInputDialog(null, "Choose account...",
"Choose bank account type", JOptionPane.QUESTION_MESSAGE, null,
accttype, // Array of acct types
accttype[0]); // First choice
// Prompt user for input
period = JOptionPane.showInputDialog(null, "Number of periods (length):");
balance = JOptionPane.showInputDialog(null, "Beginning balance:");
rate = JOptionPane.showInputDialog(null, "Interest rate (use decimal, example: .05 = 5%):");
// Make Calculate button
JButton calculate = new JButton("Calculate");
// Make 2 Labels
JLabel blabel = new JLabel("Period: " + period);
JLabel plabel = new JLabel("Balance: " + balance);
// Setup window with flow layout and exit on close
JFrame frame = new JFrame("Interest Savings Calculator Plus");
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add combo box, calc button and labels
frame.add(calculate);
frame.add(plabel);
frame.add(blabel);
frame.pack();
frame.setVisible(true);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
createAndShowGUI();
}
public Account createAccount(String type){
}
}

If you want to use the Account class for all three account types, I suggest adding a constructor to your Account class and a variable to hold the account type like so:
public class Account implements ActionListener {
...
private String accountType = null;
public Account(String accountType) {
this.accountType = accountType;
}
...
}
Then, you can create a new Account object in the createAccount() method and return it like so:
public Account createAccount(String type) {
Account account = new Account(type);
return account;
}
Then you can simply pass the account type in (which is what your "input" variable gets set to in the createAndShowGUI() method):
Account account = createAccount(input);
Otherwise, you could also simply add the accountType variable with getters and setters, and simply create a new Account and call a set method, but I recommend using a constructor that accepts those values as parameters.
Being that you probably also want the other variables to be set in your Account object, you could call the setters on the Account object you return, or you could modify your createAccount() method and the Account constructor to accept more parameters and pass them in when you create the new Account object.

Related

Java : variable reuse

I'm writing a simple Java program.
First, the program asks user to input some info like name and id of the student and uses radio button for asking whether the student is present or absent. After finishing the inputs, then program validate whether predefined student names and inputs are match or not. And check id number again and spit out if input is over 4. Lastly check radio button is true or false. If one of the above two rules get error then program will quit without executing next method.
I have three .java files. One for UI. One for validation and one for storing data.
UI.java
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class UI extends JFrame {
JTextField name = new JTextField("Name", 10);
JTextField id = new JTextField("Id", 10);
JRadioButton attendance = new JRadioButton("Present");
JButton JB = new JButton("Check");
public UI() {
super("Test");
JPanel JP = new JPanel();
JP.add(name);
JP.add(id);
JP.add(attendance);
JP.add(JB);
add(JP);
pack();
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void buttonAction(){
UI UIbutton = new UI();
UIbutton.JB.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == UIbutton.JB) {
String nameInput = UIbutton.name.getText();
int idInt = Integer.parseInt(UIbutton.id.getText());
boolean attInput = UIbutton.attendance.isSelected();
Validate.nameChk(nameInput);
Validate.idChk(idInt);
Validate.attChk(attInput);
Student studentObj = new Student(UIbutton.name.getText(), idInt, UIbutton.attendance.isSelected());
System.out.println(studentObj.name + "'s ID number is : " + studentObj.id + ".");
System.out.println(studentObj.name + " is present: " + studentObj.attendance);
System.exit(0);
}}});
}
public static void main(String[] args) {
buttonAction();
}
}
Validate.java
public class Validate {
public static void nameChk (String nameInput) {
String n1 = "Matthew";
String n2 = "John";
String n3 = "Mark";
String n4 = "Luke";
if ((nameInput.equalsIgnoreCase(n1))||
(nameInput.equalsIgnoreCase(n2))||
(nameInput.equalsIgnoreCase(n3))||
(nameInput.equalsIgnoreCase(n4))){
System.out.println("Your data is okay.");
}
else {
System.out.println("Error, wrong student name.");
System.exit(0);
}
}
public static void idChk (int idInt) {
if (idInt > 4) {
System.out.println("Your id is not correct.");
System.exit(0);
}
else {
System.out.println("Your id is correct.");
}
}
public static void attChk (boolean attInput) {
if (attInput) {
System.out.println("The student is present.");
} else {
System.out.println("The student is absent.");
}
}
}
Student.java
public class Student {
String name;
int id;
boolean attendance;
Student(String name, int id, boolean attendance) {
this.name = name;
this.id = id;
this.attendance = attendance;
}
}
What I want to know is how can I reuse output of that actionlister method somewhere else. Let say I would create foo.java class and use that studentObj variable to give grades like
System.out.println(studentObj.name+"has B+.");
Sort of.
How can I do that? How to turn that variable into global?
This can be achieved in different ways.
Quite simple, but not a good practice would be to create a Singleton. It would contain Students objects and you'll be able to access them from anywhere. Here is example with eager singleton, but you can implement much better versions (check about singleton implementations i.e. here https://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples)
public class StudentsSingleton {
private Map<Integer, Student> students = new HashMap<>();
public Student getStudent(int id) { return students.get(id);}
public void addStudent(Student s) { students.put(s.id, s);}
private static final StudentsSingleton instance = new StudentsSingleton();
//private constructor to avoid client applications to use constructor
private StudentsSingleton(){}
public static StudentsSingleton getInstance(){
return instance;
}
}
In that case, you can access it from anywhere by getting the instance :
StudentsSingleton.getInstance().getStudent(id);
A much better solution and a good practice would be to use some Dependency Injection framework i.e. Spring. In that case, you would create a Bean and inject it whenever it is needed to use.

How to add Multiple objects using indexes in a ArrayList

I'm doing a menu-based system where it will calculate my monthly rent using specific variables (double - monthlyRent, double waterBill, double energyBill etc.)
The program starts with prompting the user to select an option:
(1) create a budget invoice (this is where a projected monthly rent invoice will be calculated)
When the user selects this option I want to use an ArrayList to store the monthly rent invoices. I have a variable where the user can put an InvoiceID to search an already existing monthly rent invoices or delete etc.
My problem is how to use specific indexes in my ArrayList to input monthly rent, water bill and so forth and the next index will be a different monthly rent, waterbill, energy bill etc.). In a general sense, store multiple variable and variable types within 1 index of the ArrayList.
My ArrayList is in its own class, different from the function that I want to create to generate monthly budget invoices. My problem is how to prompt user input for each rent variable and store all of those inputs in its proper index of the ArrayList where that specific monthly invoice will be stored. The variables are double, string and int types.
import java.util.ArrayList;
public class InvoicerHub {
static ArrayList<Object> invoicerSys = new ArrayList<Object>();
}
import java.util.ArrayList;
import java.util.Scanner;
public class BudgetInvoice extends InvoicerHub {
protected double monthlyRent ;
protected double waterBill;
protected double energyBill;
protected double carRent;
protected double internetRent;
protected String invoiceID;
public int counter = 0;
static Scanner myScan= new Scanner(System.in);
public double getMonthlyRent() {
return monthlyRent;
}
public void setMonthlyRent(double monthlyRent) {
this.monthlyRent = monthlyRent;
}
public double getWaterBill() {
return waterBill;
}
public void setWaterBill(double waterBill) {
this.waterBill = waterBill;
}
public double getEnergyBill() {
return energyBill;
}
public void setEnergyBill(double energyBill) {
this.energyBill = energyBill;
}
public double getCarRent() {
return carRent;
}
public void setCarRent(double carRent) {
this.carRent = carRent;
}
public double getInternetRent() {
return internetRent;
}
public void setInternetRent(double internetRent) {
this.internetRent = internetRent;
}
public String getInvoiceID() {
return invoiceID;
}
public void setInvoiceID(String invoiceID) {
this.invoiceID = invoiceID;
}
public static InvoicerHub getInvoice()
{
invoicerSys = new ArrayList<>();
if (invoicerSys.isEmpty()== true)
{
} // This is where I'm stuck.

Java Inheritance Demonstration - on user input and incompatible types

I'm almost done with a Java program but I'm having a snag compiling.
This program is a demonstration on inheritance, with 4 classes (including a driver) but I'm getting 4 errors on the aforementioned driver. I also have a problem with making the program general (as to allow user input) as the data I'm trying to read in are of different types. I think I need to use valueOf somewhere, but we haven't gotten that far in my class. I apologize for the length.
Here are the specifications:
Define a class named
Payment
that
contains an instance variable of type
double
that stores the
amount of the payment and appropriate accessor and mutator methods.
Also create a method
named
paymentDetails
that outputs an English sentence to describe the amount of the payment.
Next, defi
ne a class named
CashPayment
that is derived from
Payment.
This class should
redefine the
paymentDetails
method to indicate that the payment is in cash. Include appropriate
constructor(s).
Define a class named
CreditCardPayment
that is derived from
Payment
.
This class should
contain instance variables for the name on the card, expiration date, and credit card number.
Include appropriate constructor(s). Finally, redefine the
paymentDetails
method to include all
credit card information in the printout.
Create main method that creates at least two
CashPayment
and two
CreditCardPayment
objects with different values and calls
paymentDetails
for each.
Be sure to make the program general so that a user can enter data!!!
Here is one of the error messages:
C:\Program Files\Java\jdk1.8.0_60\bin\ghp3driver.java:21: error: incompatible types: String cannot be converted to Payment
and here is the code...
import java.util.*; //new file/class
class ghp3driver {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
Payment cash1 = user_input.next();
Payment cash2 = user_input.next();
Payment credit1 =
user_input.next();
Payment credit2 =
user_input.next();
System.out.println("Cash 1 details:");
cash1.paymentDetails();
System.out.println();
System.out.println("Cash 2 details:");
cash2.paymentDetails();
System.out.println();
System.out.println("Credit 1 details:");
credit1.paymentDetails();
System.out.println();
System.out.println("Credit 2 details:");
credit2.paymentDetails();
System.out.println();
}
}
import java.util.*; //NEW FILE/CLASS
public class Payment {
private double amount;
public Payment() { //constructor
amount = 0.0;
}
public Payment(double paymentAmount) { //initializes payment amount
amount = paymentAmount;
}
public void setPayment(double paymentAmount) {
amount = paymentAmount;
}
public double getPayment() {
return amount;
}
public void paymentDetails() {
System.out.println("The payment amount is " + amount);
}
}
class CreditCardPayment extends Payment {
private String date, name, ccn;
public CreditCardPayment(double amount, String date, String name, String ccn) {
super(amount);
this.date = date;
this.name = name;
this.ccn = ccn;
}
public void paymentDetails() { //printing
System.out.println("Name on card: " + this.getName());
System.out.println("Expiration date: " + this.getDate());
System.out.println("Credit card number: " + this.getCcn());
System.out.println("The payment by credit card amount is " + getPayment());
}
public String getCcn() {
return ccn;
}
public void setCcn(String ccn) {
this.ccn = ccn;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class CashPayment extends Payment {
public CashPayment(double paymentAmount) {
super(paymentAmount);
}
public void paymentDetails() {
System.out.println("The payment cash amount is " + this.getPayment());
}
}
Your statements
Payment cash1 = user_input.next( );
Payment cash2 = user_input.next( );
Payment credit1 =
user_input.next( );
Payment credit2 =
user_input.next( );
You cannot assign a string value to a different class
Correct usage would be something like below
Payment cash1 = new Payment();
Payment cash2 = new Payment();
Payment credit1 = new Payment();
Payment credit2 = new Payment();
cash1.setPayment(new Double(user_input.next( )));
cash2.setPayment(new Double(user_input.next( )));
credit1.setPayment(new Double(user_input.next( )));
credit2.setPayment(new Double(user_input.next( )));
Also your code has a warning "Resource leak: 'user_input' is never closed"
You need to work this one out.
My suggestion you need to study Java programming language more before you start putting questions to correct your code. Your are missing basic points which are very important.

How to access ArrayList from another class [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
OK i have multiple Java files but only looking at 2 at the moment and i am doing a GUI program.
I have an arraylist of Landlords in one file with a getLandlords method that returns the array and it won't work eclipse just gives an error no matter what i try
File 1
package assignment2;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class RealEstateManage extends JFrame implements ActionListener, ListSelectionListener{
public static void main(String[] args)
{
RealEstateManage theGUI = new RealEstateManage();
}
//Initial setup for base of GUI
private JFrame jfFrame;
private JButton jbAddLandlord, jbAddProperty, jbAddLease, jbRecord, jbMaintenance, jbDisplayproperty;
private JTextArea jtaResults;
private JTextField jtfinput1, jtfinput2, jtfinput3, jtfinput4;
private JList <Landlord> jlLandlord;
private Vector<Landlord> vlist = new Vector<Landlord>();
private JPanel jpButtons = setupButtons(), jpResults = setupResults();
public RealEstateAgency R = new RealEstateAgency();
public RealEstateManage()
{
jfFrame = new JFrame ();
jfFrame.add(jpButtons, "North");
jfFrame.add(jpResults,"West");
jfFrame.setSize(900, 400);
jfFrame.setLocation(400, 300);
jfFrame.setTitle("Real Estate Management");
jfFrame.setVisible(true);
}
//Setup the buttons at the top of the GUI
public JPanel setupButtons()
{
JPanel jp = new JPanel ();
jbAddLandlord = new JButton("Add New Landlord");
jbAddProperty = new JButton("Add New Property");
jbAddLease = new JButton("Add New Lease");
jbRecord = new JButton("Record Payment");
jbMaintenance = new JButton("Maintenance");
jbDisplayproperty = new JButton("Display Properties");
jp.add(jbAddLandlord);
jp.add(jbAddProperty);
jp.add(jbAddLease);
jp.add(jbRecord);
jp.add(jbMaintenance);
jp.add(jbDisplayproperty);
jbAddLandlord.addActionListener(this);
jbAddProperty.addActionListener(this);
jbAddLease.addActionListener(this);
jbRecord.addActionListener(this);
jbMaintenance.addActionListener(this);
jbDisplayproperty.addActionListener(this);
return jp;
}
public JPanel setupResults()
{
JPanel jp = new JPanel ();
vlist.add(new Landlord("Fred Jones", "23 Hamilton Road", "0458 789 456", 456123369));
jtfinput1 = new JTextField (10);
jtfinput2 = new JTextField (10);
jtfinput3 = new JTextField (10);
jtfinput4 = new JTextField (10);
ArrayList<Landlord> Alist = R.getLandlords();
jlLandlord = new JList<Landlord>(vlist);
jlLandlord.addListSelectionListener(this);
jlLandlord.setPreferredSize(new Dimension(250, 300));
JLabel jlResults = new JLabel ("Output!");
jtaResults = new JTextArea (18, 30);
jtaResults.setEnabled(false);
jp.add(jlLandlord);
jp.add(jlResults);
jp.add(jtaResults);
return jp;
}
//List Events
#Override
public void valueChanged(ListSelectionEvent arg0) {
// TODO Auto-generated method stub
}
//Button Action Events
public void actionPerformed(ActionEvent ae) {
// Button Events
if(ae.getSource() == jbAddLandlord)
{
addLandlord();
}
if(ae.getSource() == jbAddLandlord)
{
}
}
//Add landlord function
public void addLandlord()
{
boolean inputIsOk = true;
String stName, stAddress, stNum, stBank;
long bank = 0;
JPanel myPanel = new JPanel();
myPanel.add(new JLabel("Name:"));
myPanel.add(jtfinput1);
myPanel.add(new JLabel("Address:"));
myPanel.add(jtfinput2);
myPanel.add(new JLabel("Phone:"));
myPanel.add(jtfinput3);
myPanel.add(new JLabel("Bank Account: (8-10 Digits)"));
myPanel.add(jtfinput4);
int result = JOptionPane.showConfirmDialog(null, myPanel,
"Please Enter X and Y Values", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
stName = jtfinput1.getText();
stAddress = jtfinput2.getText();
stNum = jtfinput3.getText();
stBank = jtfinput4.getText();
try{bank = Long.valueOf(stBank).longValue();
}
catch(NumberFormatException nfe){
inputIsOk = false;
}
if (inputIsOk = true){
R.addLandlord(new Landlord(stName, stAddress, stNum, bank));
}
}
// jlLandlord.updateUI();
}
}
FILE 2
package assignment2;
import java.util.*;
// The RealEstateAgency class is intended to be the central place to go to for finding
// a landlord that the system "knows" about.
public class RealEstateAgency {
private ArrayList<Landlord> allLandlords; // A way of collecting all the Landlords
public RealEstateAgency()
{
// prepare the agency for future landlords...
allLandlords = new ArrayList<Landlord>();
addLandlord(new Landlord("stName", "stAddress", "stNum", 12456897));
System.out.println(getLandlords());
}
// Method to note the provided Landlord, by adding it to the RealEstateAgency's internal ArrayList.
// Returns true if apparently successful, false if something goes wrong such as the landlord already being present.
public boolean addLandlord(Landlord whoToStore)
{
boolean success = false;
if (whoToStore == null) // ensure there is actually a parameter
success = false;
else {
if (allLandlords.contains(whoToStore)) // landlord already in the list
success = false;
else
{ // Landlord not yet in list
allLandlords.add(whoToStore); // So add this landlord
success = true;
}
}
return success;
}
// Method to obtain a landlord from the RealEstateAgency's collection of known landlords,
// by providing the full name. If no such landlord exists, null will be returned.
public Landlord getLandlord(String fullName)
{
Landlord current = null;
boolean found = false;
int index = 0;
while ((!found) && (index < allLandlords.size()))
{
current = allLandlords.get(index);
if (current.getFullName().equals(fullName))
found = true;
else
index++;
}
// If we get to here, and "found" is true, then "current" will be the matching Landlord
if (!found) // did not find a match
current = null; // so ensure we return no Landlord
return current;
}
// Method to obtain an ArrayList containing the same landlords as those which the
// RealEstateAgency knows about (but without exposing the inner ArrayList object
// so that any alterations made to the returned ArrayList won't impact the RealEstateAgency)
public ArrayList<Landlord> getLandlords()
{
ArrayList<Landlord> duplicate;
duplicate = (ArrayList<Landlord>) allLandlords.clone();
return duplicate;
}
public ArrayList<Landlord> getLandlords1()
{
return allLandlords;
}
}
Any help or suggestions would be appreciated.
The Issues i am having is in the setupResults() function and the getLandlords() function
Thanks in advance
LANDLORD CODE
package assignment2;
import java.util.*;
// The Landlord class allows you to create objects that encapsulate the key data
// about each Landlord, as well as the information about all the properties that
// they make available for rent (some of which may have current leases active).
public class Landlord {
private String fullName; // The name of the landlord
private String address; // Where the landlord lives!
private String phone; // allow for spaces in number
private long bankAccount; // To permit 10 digits, requires the 'long' data type
private ArrayList<Property> myProperties; // All properties owned by this landlord
public Landlord(String fullName, String address, String phone, long bankAccount)
{
// Simply store the parameters into the fields...
this.fullName = fullName;
this.address = address;
this.phone = phone;
this.bankAccount = bankAccount;
// prepare for future leases...
myProperties = new ArrayList<Property>();
}
// ACCESSORS for each field of basic information
public String getFullName()
{
return fullName;
}
public String getAddress()
{
return address;
}
public String getPhone()
{
return phone;
}
public long getBankAccount()
{
return bankAccount;
}
// Method to note/store another Property, where this Landlord is considered the owner of the property.
// It returns true if successfully added to the list of properties belonging to this landlord.
public boolean addProperty(Property theProperty)
{
boolean result;
if (theProperty == null) // if it is null, we ignore this method call.
result = false;
else if (!myProperties.contains(theProperty)){ // Make sure it is not already in the array list
myProperties.add(theProperty);
result = true;
}
else // This means w have already added the property, so cannot add it again.
result = false;
return result;
}
// Method to return an iterator that may be used to cycle over all leases involving this landlord.
public Iterator<Property> getPropertiesIterator()
{
return myProperties.iterator();
}
public String toString()
{
return "Landlord: " + fullName;
}
}
PROPERTY CODE
package assignment2;
// The Property class encapsulates the basic information about one property the system knows
// about: essentially the address of the property, and a reference to the Lease details of the property.
public class Property {
private String propertyAddress;
private Lease currentLease; // When null, there is no active lease (it is available).
public Property(String address)
{
this.propertyAddress = address;
this.currentLease = null; // Initially, nobody is leasing it.
}
public String getPropertyAddress()
{
return propertyAddress;
}
// no mutator for address, because it won't ever change.
// Method to return the current lease's details.
public Lease getCurrentLease()
{
return currentLease;
}
// Method to set the current Lease of this Property.
// If null is provided, the property will not have any Lease assigned to it;
// otherwise, the provided Lease will be recorded as describing the relationship for this property.
public void setCurrentLease(Lease newLease)
{
currentLease = newLease;
}
// Method to report whether or not this property is currently associated with a lease (regardless
// of whether fully paid or not)
public boolean isLeased()
{
if (currentLease == null)
return false;
else
return true;
}
public String toString()
{
return "Property: " + propertyAddress;
}
}
LEASE CODE
package assignment2;
import java.util.*;
// The Lease class encapsulates information about an individual lease of a property by a tenant.
// The data stored here includes all the tenant’s details (name, phone number) as well as
// characteristics of the lease itself such as the duration, the weekly rent amount, how long
// remains in terms of payments, what maintenance has occurred.
public class Lease {
private String tenantFullName; // The name of the person who is living in the leased property.
private String tenantPhone; // Contact number for the person. Allow a leading zero at start, spaces between sections.
private int rentRate; // The amount of rent to be paid each week.
private int leasePeriod; // Either 6 or 12, being a 6 month or 12 month agreement
private int weeksRemaining; // How many weeks remain to be paid for. Initially 26 or 52.
private ArrayList<Maintenance> maintenanceRecord; // record of all maintenance during life of lease
// Create a new lease, recording the following details:
// - tenantName: records the name of the person living in the property
// - tenantPhone: records a contact phone number for the tenant
// - rentRate: the amount of rent which is to be paid each week.
// - leasePeriod: Either 6 or 12, indicating the number of months the lease is to last for.
public Lease(String tenantName, String tenantPhone, int rentRate, int leasePeriod)
{
this.tenantFullName = tenantName;
this.tenantPhone = tenantPhone;
this.rentRate = rentRate;
if (leasePeriod == 12 || leasePeriod == 6) // Check validity of parameter
this.leasePeriod = leasePeriod;
else // if not valid, set to default of 6 month.
this.leasePeriod = 6;
// Determine (automatically) how many weeks the lease is for, and set as initial value
// for the 'weeksRemaining' field:
if (this.leasePeriod == 12)
this.weeksRemaining = 52; // a Year remains to be paid for
else
this.weeksRemaining = 26; // Only half a year remains to be paid for.
// Prepare the lease for future Maintenance records...
maintenanceRecord = new ArrayList<Maintenance>();
}
// ACCESSORS
public String getTenantFullName()
{
return tenantFullName;
}
public String getTenantPhone()
{
return tenantPhone;
}
public int getRentRate()
{
return rentRate;
}
public int getLeasePeriod()
{
return leasePeriod;
}
public int getWeeksRemaining()
{
return weeksRemaining;
}
// Method to reduce the number of weeks remaining to be paid over the period of the lease.
// If the parameter is in excess of the current number of remaining weeks, the method will
// return false, otherwise it returns true and adjusts the number of remaining weeks.
public boolean reduceWeeksRemaining(int howMuch)
{
boolean result;
if (howMuch > weeksRemaining)
result = false;
else
{
weeksRemaining -= howMuch; // Reduces how many weeks remain unpaid.
result = true;
}
return result;
}
// Method to add another maintenance information record to this lease's list of maintenance records.
public void noteMaintenance(String reason, double cost)
{
Maintenance maintInfo = new Maintenance(reason,cost);
maintenanceRecord.add(maintInfo);
}
// Method to return an Iterator that may be used to cycle over all maintenance records for this lease
public Iterator<Maintenance> getMaintenanceRecords()
{
return maintenanceRecord.iterator();
}
}
MAINTENANCE CODE
package assignment2;
// The Maintenance class is used to represent an individual occurrence of Maintenance
// and records the cost and description of the maintenance.
public class Maintenance {
private String reason;
private double cost;
public Maintenance(String reason, double cost)
{
this.reason = reason;
this.cost = cost;
}
// ACCESSORS:
public String getReason()
{
return reason;
}
public double getCost()
{
return cost;
}
// Gives a explanation of the cost and reason represented by this Maintenance object.
public String toString()
{
return "$" + cost + " for " + reason;
}
}
The reason is that you initialize setupResults() before R.
change:
private JPanel jpButtons = setupButtons(), jpResults = setupResults();
public RealEstateAgency R = new RealEstateAgency();
public RealEstateManage()
{
to
private JPanel jpButtons;
private JPanel jpResults;
public RealEstateAgency R = new RealEstateAgency();
public RealEstateManage()
{
jpButtons = setupButtons();
jpResults = setupResults();
As a sidenote:
You take the result as:
ArrayList<Landlord> Alist = R.getLandlords();
but never use that value.
Maybe you meant to write:
ArrayList<Landlord> Alist = R.getLandlords();
jlLandlord = new JList<Landlord>(Alist.toArray(new Landlord[0]));
^ ^^^^^^^^^^^^^^^^^^^^^^^^^
but you did not.

error checking not registering

im sure theres a simple answer to this, but when i set my balance to a negative number, i want the system to print an error, at the moment, it just prints the negative number to the console, would anyone be able to help me as to why this may be happening. Any replies appreciated.
package Assignment1;
public class Customer
{
private String name;
private String address;
private int balance;
public Customer(String nameParam, String addressParam, int balanceParam)
{
name = nameParam;
address = addressParam;
balance = balanceParam;
}
public void setName(String nameParam)
{
name = nameParam;
}
public String getName()
{
return name;
}
public void setAddress(String addressParam)
{
address = addressParam;
}
public String getAddress()
{
return address;
}
//I want the system to print an error should the balanceParam be less than 0
public void setBalance(int balanceParam)
{
if (balanceParam >= 0)
{
balance = balanceParam;
}
else
{
System.out.println("Error: Invalid balance");
}
}
public int getBalance()
{
return balance;
}
public static void main(String[] args)
{
Customer customer1 = new Customer("Tom", "High Street", 100);
Customer customer2 = new Customer("Mary", "Low Street", 110);
//The balance for customer3 is set to a negative number
Customer customer3 = new Customer("John", "Middle Street", -10);
System.out.print(customer1.getName() + "\t");
System.out.print(customer1.getAddress()+ "\t");
System.out.println(customer1.getBalance());
System.out.print(customer2.getName()+ "\t");
System.out.print(customer2.getAddress()+ "\t");
System.out.println(customer2.getBalance());
System.out.print(customer3.getName()+ "\t");
System.out.print(customer3.getAddress()+ "\t");
System.out.println(customer3.getBalance());
}
}
You never call the method setBalence which prints the error.
To have the error printed as soon as you construct the Customer object change your constructor to use the setter methods for the class fields
public Customer(String nameParam, String addressParam, int balanceParam)
{
setName(nameParam);
setAddress(addressParam);
setBalance(balanceParam);
}
Also you might want to prevent the construction of such an object or setting a negative balance into an existing object by throwing an exception:
public void setBalance(int balanceParam) {
if (balanceParam < 0) {
throw new IllegalArgumentException("Error: Invalid balance");
}
balance = balanceParam;
}
Note that the check occurs in your setBalance() method, but you never call this method. In particular, your constructor sets the balance field directly without a similar check One way to fix this (and reduce duplication at the same time) is to call setBalance() (and the other setters) from your constructor.

Categories