I have a page where I can edit an object's values in Java. However, I would need to store and pass the object's old values as well for the Stored Procedure.
For this, I duplicated the object like so:
public void onClickEdit(Education e) {
Education edOld = new Education(e);
Education edNew = new Education(e);
goToPage(a);
}
I also made it so that the user will only edit edNew in the edit page.
The Education class has a constructor that sets another Education class' attributes as its own, like so:
public class Education {
private int educationID;
private String educationName;
private String educationStatus;
public Education() { }
public Education(Education e) {
educationID = e.getEducationID();
educationName = e.getEducationName();
educationStatus = e.getEducationStatus();
}
// setter-getters ...
}
My question is, would it be better on the memory to have a single class that has attributes for new and old attributes - like this:
private int educationID;
private String educationName;
private String educationStatus;
private int old_educationID;
private String old_educationName;
private String old_educationStatus;
or is the way that I am doing it fine as well?
simply i have this file reading it and storing it into array and then want to call the values back later to print them
my text file
`101
12-7-2017
14-7-2017
some name
00000.. phone number
520
29-8-2017
1-9-2017
some name
00000.. phone number
1020
30-12-2017
1-1-2018
some name
00000.. phone number`
this the main test code
public class test {
public static void main(String[] args) throws ParseException, FileNotFoundException{
Scanner res = new Scanner (new File("reservations.txt"));
int z=0;
do{
int room_numb = res.nextInt();
String cInr=res.next();
String cOutr=res.next();
String Fname=res.next();
String Lname=res.next();
String phone_numb=res.next();
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
Date cIn = df.parse(cInr);
Date cOut = df.parse(cOutr);
Reservation.reserv[z]=new Reservation (room_numb, cIn, cOut, new Guest(Fname, Lname, phone_numb));
z=z+1;
}while(res.hasNext()==true);
Guest FLnames=Reservation.reserv[0].getguest();
System.out.println(FLnames);
}
my classes are these 3
reservation
public class Reservation {
static Reservation[] reserv= new Reservation[200];
Guest guest;
int room_numb;
Date in, out;
public Reservation(int room_numb, Date in, Date out, Guest g) {
this.room_numb = room_numb;
this.in = in;
this.out = out;
g= guest;
}
public int getroom_numb(){
return room_numb;
}
public Date getin(){
return in;
}public Date getout(){
return out;
}public Guest getguest(){
return guest;
}
Room
public class Room {
int room_numb;
String indate;
public void setRoom(int i) {
room_numb =i;
}
public int getRoom(){
return room_numb;
}
and guest
public class Guest {
String Fname;
String Lname;
String phone_number;
public Guest(String fname, String lname, String phone_numb ){
Fname=fname;
Lname=lname;
this.phone_number=phone_numb;
return;
}
public String getFname(){
return Fname;
}
public String getLname(){
return Lname;
}
public String getphone_number(){
return phone_number;
}
}
i have been able to get all variables such as room numb/checkin date and checkout date/ but when ever i ask for guest through
Guest FLnames=Reservation.reserv[0].getguest();
System.out.println(FLnames);
it gives me null which mean it doesn't reference to anything
so i am not able to use String Fname=Reservation.reserv[0].getguest().getFname();
so how to get the data from guest in reservation array?
Note: i am new to java so be gentle with ma please :) also the sysout is just for testing in the main method
Thanks :).
I'm not going to fix your code for you. Doing that is part of your homework. However, here are a couple of hints to start you in the right direction.
Hint: Look carefully at how your Reservation constructor (tries to) initialize the object's fields. See the problem?
Hint 2: The problem that tripped you up is that getguest() is returning null .......
While I have your attention, there are numerous style errors in your code, but the worst is your complete disregard of the Java converions for identifier names:
A class name must start with a capital letter and be in camel-case: Test not test.
A method or variable name must start with a lower case and be in camel-case; e.g. getGuest not getguest.
We don't need or use "hungarian" notation in Java. The type of a variable is expressed in the type declaration.
Your choice of variable names is inconsistent and "uninspired".
And "numb" is what happens when your fingers get cold.
I need to create a variable of either data type on runtime (via scanner class)
This is what my assignment asked
"A selling arrangement could be an offered price OR an auction date"
This is what i have created but not sure if it is correct..
public class SellingArrangement {
private Object dateOrPrice;
public SellingArrangement()
{
}
public void setDateOrPrice(String price)
{
dateOrPrice = new Object();
dateOrPrice = price;
}
public void setDateOrPrice(Double price)
{
dateOrPrice = new Object();
dateOrPrice = price;
}
I have done something similar before (when an API may return JSON or XML)
However, you have two sets of two choices here - the input can either be a String or a Double, and that input can either represent a Date or a Price.
Instead of using an Object, I would just create two separate fields and populate the correct one using two separate constructors like this.
public class SellingArrangement {
private Date date;
private Price price;
public SellingArrangement(String input)
{
if ( // String is a price ) {
this.price = new Price(input);
}
if ( // String is a date ) {
this.date = new Date(input)
}
}
public SellingArrangement(Double input)
{
if ( // Double is a price ) {
this.price = new Price(input);
}
if ( // Double is a date ) {
this.date = new Date(input)
}
}
}
Of course, I am assuming you can figure out some way to validate whether the String or Double you are getting as input is a date or a price, and that you have constructors which will take a String / Double for each type. Treat this as pseudocode...
However as others have mentioned in comments if you dont have to do this with a single class, it would be better to use another method entirely...
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.
I am new to Java. This is giving out an error.
private class applicantInfo {
int Id;
double quality;
}
private class allApplicants {
applicantInfo[] applicantArr = new applicantInfo[20];
}
public void newGame {
allApplicants applicants = new allApplicants();
applicants.applicantArr[0].Id = 5;
}
I am getting an error at the point of applicants.applicantArr[0].Id = 5;.
All I want to do is similar to this in C:
typedef struct _applicantInfo{
int Id;
double quality;
} applicantInfo;
typedef struct _allApplicants {
applicantInfo applicantArr[20];
} allApplicants;
int main () {
allApplicants applicants;
applicants.applicantArr[0].Id = 5;
}
How can I do that in Java?
The difference between Java and C arrays is that C initialises all the values in the Array, whilst Java sets them to null. So when you call
applicants.applicantArr[0].Id = 5;
You will get a NullPointerException, as applicants.applicantArr[0] is null.
You need to create a new applicantInfo and put it into the array before accessing it:
allApplicants applicants = new allApplicants();
applicants.applicantArr[0] = new applicantInfo();
applicants.applicantArr[0].Id = 5;
you need to do this in your newGame():
applicantInfo item = new applicantInfo();//first create a applicantInfo object
item.Id= 5;//set the object properties
applicants.applicantArr[0]= item;//assign the object to the array
this is because Arrays work in a different way in Java than those in C. Take a look at this
and also here is a tutorial to get you started with.
I would suggest a high-level structure for your code with comments and TODOs, you can fill in the details. And the last part, where I suggest the structure for newGame method, will help you get rid of the error you are getting.
The structure for ApplicantInfo class:
public class ApplicantInfo {
private int ID;
private double quality;
// Constructor to create an instance with the specified ID value
public ApplicantInfo(int id){
// TODO: Initialize the value for ID field
}
// Method to get the value for ID
public int getID(){
// TODO: return value of ID field
}
// Method to set the value for ID
public void setID(int id){
// TODO: set the value for ID field
}
// Getter and setter methods for "quality"
// on the lines of the above methods
}
The structure for AllApplicants class:
public class AllApplicants {
private ApplicantInfo[] applicantArr = new ApplicantInfo[20];
// Method to get the applicant info at a given index
public ApplicantInfo getApplicant(int index){
// TODO: Get the applicant from the array present at the specified index
}
// Method to add an applicant info at a given index
public boolean addApplicant(ApplicantInfo applicant, int index){
// TODO: Try to add the specified applicant to the array at the specified index
// Return true to indicate that the applicant was successfully added,
// Return false to indicate that an applicant is already present at the specified index
}
}
As this is just a skeleton to
The structure for newGame method:
public void newGame {
AllApplicants applicants = new AllApplicants();
// In order to achieve doing "applicants.applicantArr[0].Id = 5;", you
// need to do the following.
// Create a new applicant info with ID as 5
ApplicantInfo applicant = new ApplicantInfo(5);
// Add the applicant to the applicant array at index 0
applicants.addApplicant(applicant, 0);
}
In addition to reading about array, as mentioned by #codeman, you may also want to take a look at Java Naming Convention