I am trying to create a method to list the elements in an ArrayList, but the method only returns the values of the most recent object:
The object:
//Constructor for guests at the hotel
public Guest (String name, String checkinDate, String checkoutDate, double depAmt)
{
gstName = name;
checkIn = checkinDate;
checkOut = checkoutDate;
deposit = depAmt;
}
Current objects in the ArrayList:
//Fills the roster with three guests to start the program
public static void fillGuest()
{
Guest guest1 = new Guest("Mike P.", "2/13/16", "2/23/16", 360.00);
guestList.add(guest1);
Guest guest2 = new Guest("Randall M.", "4/10/16", "4/17/16", 120.00);
guestList.add(guest2);
Guest guest3 = new Guest("Bo-Diddly.", "4/20/16", "4/23/16", 600.00);
guestList.add(guest3);
}
Method to list the objects in the ArrayList:
public static void returnGuests()
{
System.out.println("Currently checked in " + guestList.size() + " guests:");
for (int i = 0; i <= guestList.size() - 1; i++)
{
System.out.println(guestList.get(i));
}
}
The output:
Currently checked in 3 guests:
Bo-Diddly. 4/20/16 4/23/16 600.0
Bo-Diddly. 4/20/16 4/23/16 600.0
Bo-Diddly. 4/20/16 4/23/16 600.0
Enter command:
How do I display the individual object parameters of each Guest object?
Your Guest object should look like below. Note the lack of the static modifier on the fields. Also, note the use of the this keyword. If you use that with a static variable, then your IDE should give you a warning that it will be interpreted as a MyClass.var instead of this.var.
Your problem is that all Guest objects will have the last set of variables as you create new Guest objects. You need to use "instance" variables instead of "class" variables.
If you would like to read more on the topic of static "class" variables, please see Understanding Class Members.
public class Guest {
String gstName, checkIn, checkOut;
double deposit;
public Guest (String name, String checkinDate, String checkoutDate, double depAmt)
{
this.gstName = name;
this.checkIn = checkinDate;
this.checkOut = checkoutDate;
this.deposit = depAmt;
}
}
Related
I'm hoping someone can help me out with a question that I've been stuck on for quite a while.
Just to clarify the scenario. There is a show being held in a theatre that can hold 180 people. They allow online bookings that are written to a text file "bookings.txt" Individual bookings are single that only have a seat, contact and payment status record. Whereas group bookings have seats, a contact number, payment status, group name and group size records.
So far I have created the Bookings and GroupBookings classes. I'll show them below:
/**
*
* #author OP
*/
public class Booking
{
public String seat;
public String contact;
public double cost;
public boolean paid;
//Constructor
public Booking(String st, String ct, int cost, boolean pd)
{
seat = st;
contact = ct;
this.cost = cost;
paid = pd;
}//end of Booking
//Getters
public String getSeat()
{
return seat;
}//end of getSeat
public String getContact()
{
return contact;
}//end of getContact
public boolean isPaid()
{
return paid;
}//end of isPaid
public double getCost()
{
//Determining what discount should be applied to their seat location
if (seat.contains("A") || seat.contains("B") ||
seat.contains("C") || seat.contains("D"))
{
cost = 200;
}
else
{
if (seat.contains("E") || seat.contains("F") ||
seat.contains("G") || seat.contains("H"))
{
cost = 160;
}
else
{
if (seat.contains("I") || seat.contains("J") ||
seat.contains("K") || seat.contains("L"))
{
cost = 120;
}
}
}//end of nested if statement
return cost;
}//end of getCost
#Override
public String toString()
{
return seat + "\t" + "R" + cost + "\t" + paid;
}//end of toString
}//end of class booking
/**
*
* #author OP
*/
public class GroupBooking extends Booking
{
private String groupName;
private int groupSize;
public GroupBooking(String st, String ct, boolean pd, String gn, int gs)
{
//Variables from previous class (using inheritance)
super.seat = st;
super.contact = ct;
super.paid = pd;
//New variables for this class
groupName = gn;
groupSize = gs;
}//end of GroupBooking
#Override
public double getCost()
{
cost = super.getCost();
for (int i = 0; groupSize % 4 > i; i++)
{
cost = cost - 60;
i++;
}//end of for loop
return cost;
}//end of getCost
public int getGroupSize()
{
return groupSize;
}//end of getGroupSize
public String getGroupName()
{
return groupName;
}//end of getGroupName
#Override
public String toString()
{
return seat + "\t" + "R" + cost + "\t" + groupName;
}//end of toString
}//end of class GroupBooking
Now for the question that I am stuck on:
A new class has to be created called BookingManager. From there I have to declare two instance variables in the class of one-dimensional array that can be used to store up to 180 Booking or GroupBooking objects. An integer counter must also be created to keep track of how many Bookings are stored in the array. (These two instance variables should not be accessible from outside the class)
I'm still a newbie in coding and I'm unsure of what to do here. The follow-up question is also giving me difficulties:
A contractor then has to be created to read the information from the text file "bookings.txt". Each line either contains a single Booking or a GroupBooking object. Read each line from the file and instantiate the appropriate type of object (Booking or GroupBooking) and add it to the array. (Note in the case of GroupBooking you must create an object in the array for each member of the group. Exp for a group of six you have to have six separate GroupBooking objects in the array.)
I know a file scanner is needed from the second question but I have no idea whether to use a for loop or an if statement to differentiate between a single booking or a group booking.
If anyone can help I would truly appreciate it. This topic is still very new to me.
To prevent a variable being accessible outside a class declare the variable "private". e.g.
private String costtotal="";
An instance variable "is not" static ("is not" a class member variable), and are a global variable only declared at the top of the class code below the import statements, so exist until the class exits.
In your manager class you need a global variable array Booking class
Booking[] bookings;
private String costtotal=""; // e.g.
// in the constructor read the bookings file and find the number of bookings made
//int totalbooked=...whatever reading the file data counts to of bookings made;
bookings=new Booking[totalbooked];
// create and fill each Booking object and assign it to its index on the array in a loop
bookings[loopcount]=new Booking(st,ct,cost,pd);
Different schemes of class systematics of coding
// bean syntax in a java bean framework class type
public void setCosttotal(String costtotal){
this.costtotal=costtotal;
}
//bean syntax
public String getCosttotal(){
return costtotal;
}
// normal non bean syntax 1
public String costTotal(String csttot){
return (String)csttot;
}
// somewhere else in code in scope to global variable
costtotal=costTotal(valuein);
// normal non bean syntax 2
public String costTotal(String csttot){
costtotal=csttot;
return costtotal;
}
Okay, so I'm working on a homework assignment where I have a staff of 10 salespeople. We have a contest for the greatest number of sales. The assignment wants the user to enter 10 integer values as a number of sales and then once they've all been entered the salesperson with the highest value will be returned.
What she wants:
A Class "Sales" with (String name and Integer sales) values.
A while loop where the user inputs integers for number of sales
What I'm attempting to do. I assume the names of the salespeople at the company are known, so I just created an array strSalesPerson of 10 fictitious names. I created a counter salespersonCounter to create the counter for the while loop for user input. I'm trying to basically create salesperson1, salesperson2, salesperson3, and so on by creating a variable with the string "salesperson" concatenated with the counter. I want to use that as the name of the instance for each salesperson entered into the Sales Class.
Sales Class
Just for reference, the class I've created and trying to create instances of is as follows:
private String salesname;
private Integer numsales;
public Sales(String name, Integer sales) {
this.salesname = name;
if (sales >= 0.0) {
this.numsales = sales;
}
}
// Setter for name
public void setName(String name) {
this.salesname = name;
}
// Getter for name
public String getName() {
return salesname;
}
// Setter for Sales
public void setSales(Integer sales) {
if (sales >=0) {
this.numsales = sales;
}
}
// Getter for Sales
public int getSales() {
return numsales;
}
} // End of Class
TestSales
This is where I will get the user input and save it as an instance of the Sales class. However, right now I'm just going to use the current instance from the array of names and the static integer 3 to ensure that I get the other pieces functioning correctly and then I'll switch over to user inputs from there.
// Import Scanner
import java.util.Scanner;
public class TestSales {
public static void main(String[] args) {
// create scanner to obtain input from command window
Scanner input = new Scanner(System.in);
// Initialize variables
int salespersonCounter = 1;
// Fill Salesperson names
String[] strSalesPerson = new String[]{"Mark Hasselback","Gary Moore","Shelly Hemingway", "Susan Meagre","Nick Pantillo","Craig Grey","Alice Reese","Mickey Greene","Chaz Ramirez","Kelly Southerland"};
while (salespersonCounter <=10) {
String salespersoninstance = ("salesperson"+ salespersonCounter);
String currsalesperson = strSalesPerson[salespersonCounter -1];
System.out.printf("%s");
Sales salespersoninstance = new Sales(strSalesPerson[salespersonCounter -1],);
System.out.printf("%s is %s!%n",salespersoninstance,currsalesperson);
salespersonCounter += 1;
}
}
}
The problem I am running into is here:
Sales salespersoninstance = new Sales(strSalesPerson[salespersonCounter -1],3);
instead of accepting the string value of salespersoninstance (in this case salesperson1) as the name of the instance of the Sales Class, it is telling me that salespersoninstance is a duplicate local variable. It is interpreting it I guess as me trying to define a new variable with the same name as one I've already declared?
Basically what I want is with the while counter, create a string variable salesperson1, salesperson2, salesperson3 and so on with "salesperson" + salespersonCounter, and use that resulting string to name the instance of the Sales class. That way I can then say Sales salespersoninstance = new Sales(strSalesperson[salespersoncCounter -1], userinput)
To help you a bit forward:
String[] salePersonNames = new String[]{"Mark Hasselback", "Gary Moore", "Shelly Hemingway", "Susan Meagre", "Nick Pantillo", "Craig Grey", "Alice Reese", "Mickey Greene", "Chaz Ramirez", "Kelly Southerland"};
for (int i = 0; i < salePersonNames.length; i++) {
Sales salesPerson = new Sales(salePersonNames[i], 3);
System.out.printf("%s is %s!%n", salesPerson.getName(), salesPerson.getSales());
}
I've started writing my own Java program during my freetime called the "Book A Ticket Machine", it's a Java console program with no GUI. It will Ask you for your FullName, FrequentFlyer ID, Age, then match you to your designated airline and flight number. While you travel your fuel will decrease and when it lands the fuel will fill up (I will create a fill method for this). I am having problems with calling a method from outside a scope.
Currently I have two files:
Flights.java --> Launching file. Linked with flightUserDatabase.
flightUserDatabase.java --> Contains all methods and class/blueprints all username, age, frequentFlyer, etc.
Code from Flights.java:
import java.io.Console;
public class Flights {
public static void main (String[] args) {
Console console = System.console();
//Book a Ticket Machine
//From Database otherwise Name not found on Database. Put Database in Another Class. Call it flightUserDatabase.
/* firstName: DONE
lastName: DONE
frequentFlyerID: Otherwise Invalid Number parseInt
Age: parseInt
FUEL MINUS AND FUEL ADD WHEN LAND.
*/
flightUserDatabase database = new flightUserDatabase();
System.out.println("Enter Creditials: ");
database.getDatabase();
String airline = console.readLine("ENTER YOUR AIRLINE: ");
String flightNumber = console.readLine("ENTER YOUR FLIGHT NUMBER: ");
String gate = "B7"; /* Declare data type String called "gate" */
//Next Version, Generate Random Number
System.out.println("This is an automated system. Please Wait...");
System.out.printf("%s %s is Departuring # Gate:%s \n", airline, flightNumber, gate); /* Use printf from java.io.Console library, then output Gate and Flight Number */
/* Notes: Data Types
> String name = "Ohm";
> int age = 42;
> double score = 95.5;
> char group = 'F';
*/
}
}
Code from flightUserDatabase.java:
import java.io.Console;
//Book a Ticket Machine
class flightUserDatabase {
Console console = System.console();
public String fullName;
public boolean getDatabase() {
boolean namesInDatabase;
do {
fullName = console.readLine("ENTER YOUR FULLNAME: ");
namesInDatabase = (fullName.equals("Ohm Passavudh") || fullName.equals("Matt"));
if (!namesInDatabase) {
console.printf("Sorry, that name is not in our database yet. \n");
}
if (namesInDatabase) {
console.printf("Welcome, Mr. %s \n", fullName);
}
} while(!namesInDatabase);
return namesInDatabase;
}
//If Ohm: FFID = 1234569
//If Matt: FFID = 246810
//FFID == FrequentFlyerID
/* Get name from inside scope fullName namesInDatabase variable */
public boolean frequentFlyerID()
I HAVE PROBLEMS HERE!!! I WANT TO SET Ohm's FFID to 1234569. But how to I determine if the user enters Ohm or Matt. I cannot access the String fullName from the other scope. I hope you understand me. If there is any misunderstanding I can clarify.
}
First, please, do work on your formatting, reading that code was awful.
You can create a class field and a getter in flightUserDatabase, so you can get the name after you've determined the name is in the database.
Or you can return it with getDatabase()
Like this...
public String getDatabase()
{
String fullName;
...
return fullName;
}
After all, you're not using that boolean.
... or this ...
class flightUserDatabase
{
private String fullName = "";
...
public String getName()
{
return this.fullName;
}
}
You have to initialize variable public String fullName; -> public String fullName = "";
Work on formating code
Name class begin from upper sign in your case FlightUserDatabase
Remember about encapsulation (private variable)
I am having issues with objects and classes.
I had to define two classes:
Course: a course has a code, an name and a number of credits
Teacher: a teacher has a first name and last name. He can be asked his full name.
So far so good, I got no issue with them, but I have to do next assignment which I was trying to do in the last 2 days and I could not find a proper answer:
Extend the code of the class teacher. A teacher also has a list of courses he can teach. Add an array of Courses to the code. Also add a function addCourse(Course aCourse) to the code. Courses can also be removed from teachers.
I could do everyting in my way but no clue on how to create the addCourse(Course aCourse) method.
Find below my coding, but it must be according to the method described:
public class Course {
private String courseCode;
private String courseName;
private String numberOfCredits;
public Course(String courseCode, String courseName, String numberOfCredits) {
super();
this.courseCode = courseCode;
this.courseName = courseName;
this.numberOfCredits = numberOfCredits;
}
public void print() {
System.out.println(courseCode + "\t" + courseName + "\t" + numberOfCredits);
}
public static void main(String[] args) {
Course[] courseArray = new Course[4];
System.out.println("Code" + "\t" + "Name" + "\t" + "Credits");
courseArray[0] = new Course("001", "Hist", "3");
courseArray[1] = new Course("002", "Phy", "3");
courseArray[2] = new Course("003", "Math", "3");
courseArray[3] = new Course("004", "Log", "3");
for (int i = 0; i < courseArray.length; i++) {
courseArray[i].print();
}
}
}
Arrays are fixed length collections of objects, so you'll need to decide how big your array should be. Let's call the length of your array MAX_COURSES. A more advanced solution might resize the array when required, but I get the impression this is beyond the scope of your course.
So you need to define the Course[] array as a field of your Teacher class. The syntax of array declarations is quite easy to research, so I won't put that in here. Just make sure your array length is equal to MAX_COURSES.
Now, to add courses to the array, you need to know where to put them. To keep track of the next free position of the array, the easiest thing to do is to declare a field in your class:
private int numCourses = 0;
Now, when you add a new course, insert the course into the index specified by numCourses. Make sure you increment numCourses after you've added the course.
Finally, you ought to test to see if your array is full before you agree to insert a new course into the array, i.e. check if numCourses is smaller than MAX_COURSES. If it's not, you need to throw an exception.
I would recommend using a collection (such as a List) rather than an array. The code would look something like:
public class Teacher {
private final String firstName;
private final String lastName;
private final List<Course> courses = new ArrayList<Course>();
public Teacher(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public void addCourse(Course course) {
courses.add(course);
}
}
Based on that example, you should be able to add the removeCourse method yourself, and any other method you need to operate on the list of courses.
If you want to return the list as an array, you could always convert it, e.g:
public Course[] getCourses() {
return courses.toArray(new Course[courses.size()]);
}
If you really need to use an array for the data structure based on your assignment, something you can try when adding and removing courses, is to construct a list from the array of courses, add or remove a course from that list, the convert the list back to an array of courses.
There's really 3 options here.
Option 1
If you're allowed to use List constructs:
private List<Course> courses = new ArrayList<Course>();
public void addCourse(Course aCourse)
{
if (aCourse == null)
{
return;
}
courses.add(aCourse);
}
Option 2
The uses arrays, but it doesn't scale. Assume that a teacher can only have a maximum of X courses, in my example 10:
// Yes, I stole Duncan's variable names
private final int MAX_COURSES = 10;
private int numCourses = 0;
private Course[] courses = new Course[MAX_COURSES];
public void addCourse(Course aCourse) {
if (aCourse == null)
{
return;
}
if (numCourses >= courses.length)
{
return;
}
courses[numCourses] = aCourse;
numCourses++;
}
Option 3
This is identical to the previous item, but is a bit smarter in that it can resize the array... by creating a new one using the static method Arrays.copyOf
// Yes, I stole Duncan's variable names
private final int MAX_COURSES = 10;
private int numCourses = 0;
private Course[] courses = new Course[MAX_COURSES];
public void addCourse(Course aCourse) {
if (aCourse == null)
{
return;
}
if (numCourses >= courses.length)
{
int size = courses.length * 2;
courses = Arrays.copyOf(courses, size);
}
courses[numCourses] = aCourse;
numCourses++;
}
So I'm writing a program for an assignment where I store Patients into a TreeSet. The problemn I'm having is I have to implement a method to discharge a specefic patient from the TreeSet.
for(int i = 0; i < 10 ; i++){
Random ag = new Random();
int age = ag.nextInt(99) + 1;
Names randomname = Names.getRandom();
String name = randomname.name();
String sex;
if(Math.random() > 0.5)sex = "female";
else sex = "male";
Random sn = new Random();
int serial = sn.nextInt(10000) + 1;
Address randomAddress = Address.getRandom();
String address = randomAddress.name();
Hospital.admitPatient(new Patient(age, name, sex, serial, Birthday.produceBirthday(), address));
}
So Thats how I am looping to get the Patients info and stats for the Patient Object. The admit patient method adds them to the TreeSet.
public static void admitPatient(Patient obj){
if(numofPatients < maxPatients){
patientList1.add(obj);
}
}
The Problem I'm having is withbthe Discharge patient method. Where I don't know what to put in the method
public static void dischargePatient(What do i put here in the driver when i call this method?){
patientList1.remove(w/e i put up there);
}
Since I didn't name the Objects of patients when creating them but just inserted them straight into the TreeSet I'm not sure exactly how to call them when i call the discharge patient method.
As you usually want to work with selected objects (patients) and not the whole list, you need a way to identify them somehow (for example by name or ID).
Since add and remove are similar, your dischargePatient method will be similar as well. Try
public static void dischargePatient(Patient patient) {
patientList1.remove(patient);
}
To retrieve a patient with a certain ID, you may iterate through your set and return it:
public Patient getPatientByID(String id) {
for (Patient patient : patientList1) {
if (patient.getID().equals(id)) {
return patient;
}
}
}
To remove a patient with ID "1234abc", you could do the following:
dischargePatient(getPatientByID("1234abc"));
Using this pattern, you rebuild the functionality of the map datastructure. Thus it might be better to use a Map (e.g. HashMap<>). Code will be reduced to operations like:
Map<String, Patient> patients = new HashMap<>();
patients.put("1234abc", patient1);
patients.remove("1234abc");
Full code for your example:
public static void admitPatient(Patient patient) {
if(numofPatients < maxPatients){
patients.put(patient.getID(), patient);
}
}
public static void dischargePatient(String id) {
patients.remove(id);
}