TreeSets and removing specific unnamed Objects - java

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);
}

Related

Listing Parameters of an Object in an ArrayList

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;
}
}

How to add a Course object to an array via an addCourse() method

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++;
}

Using ArrayList as function call Java

public class TestClass extends BaseClass {
public void getquote() {
String FirstName = "Sam";
String LastName = "Gayle";
String Email = "somename#somename.com";
String Password = "test1234";
CallGetQuote(FirstName, LastName, Email, Password);
}
private void CallGetQuote(String... var) {
for (int i = 0; i < var.length; i++) {
driver.findElement(By.id("first-name")).sendKeys(var[i]);
driver.findElement(By.id("last-name")).sendKeys(var[i]);
driver.findElement(By.id("join-email")).sendKeys(var[i]);
driver.findElement(By.id("join-password")).sendKeys(var[i]);
// driver.findElement(By.name("btn-submit")).click();
}
}
}
`I would like to fill in the objects using a loop rather than hard coded index number as mentioned. Above is what I wrote, at the moment, all text boxes are filling with all values. Please help :(
Thanks.`
You can use varargs, more informations could be found in the JLS:
You can use a construct called varargs to pass an arbitrary number of
values to a method. You use varargs when you don't know how many of a
particular type of argument will be passed to the method.
So, your code will be something like:
public void getquote() {
String firstName = "Sam";
String lastName = "Gayle";
String email = "somename#somename.com";
String password = "test1234";
CallGetQuote(FirstName, LastName, Email, Password);
}
public void CallGetQuote(String... var) {
// add your elements to a List
List<MyElements> inputElements = new ArrayList<MyElements>;
inputElements.add(driver.findElement(By.id("first-name")));
inputElements.add(driver.findElement(By.id("last-name")));
inputElements.add(driver.findElement(By.id("join-email")));
inputElements.add(driver.findElement(By.id("join-password")));
// iterate over the List to send keys
for (int i = 0; i < var.length; i++) {
inputElements.get(i).sendKeys(var[i]);
}
}
May be instead of passing array/list you can create a class containing all the variable and accessors and modifier functions for each variable. Create the object of the class in getQuote() and append the values in the same function. Later you can simply pass the object.
And whenever you have new attribute you can simply add the attributes to the class and use the object anywhere.
considaring that you have only specified number of inputs on web page you may try like this.
public void getquote() {
String FirstName = "Sam";
String LastName = "Gayle";
String ZipCode = "10104";
String PhoneNumber = "212-225-8558";
CallGetQuote(FirstName, LastName, ZipCode, PhoneNumber);
}
public void CallGetQuote(String... var) {
List<Webelement> inputs = driver.findElements(By.tagName("input"));
for (int i = 0; i < var.length; i++) {
inputs.get(i).sendKeys(var[i]);
}
}
You may have to change the order of strings you are sending.

How to access values stored in ArrayList in Java?

I'm a total newbie to Java, and until now all I've done was draw some shapes and flags. I'm struggling to understand the code I've been given. I need to access values stored in an ArrayList within another class. I'm not sure I'm making any sense, so here are the two classes Seat and Mandate:
package wtf2;
import java.util.*;
public class Seat {
public int index;
public String place;
public int electorate;
public String mp;
public String party;
public String prev;
public ArrayList<Mandate> results;
public Seat(int index, String place) {
this.place = place.trim();
this.index = index;
this.results = new ArrayList<Mandate>();
}
public void addMandate(Mandate m) {
//First candidate is always the MP
if (mp == null) {
mp = m.candidate;
party = m.party;
}
results.add(m);
}
public String toString() {
return "[" + this.index + "," + this.place + "]";
}
}
class Mandate {
public String candidate;
public String party;
public int vote;
public Mandate(String candidate, String party, int vote) {
this.candidate = candidate;
this.party = party;
this.vote = vote;
}
}
The main class contains code that feeds data from 2 text files into Seat and Mandate. From there I managed to access the date in Seat. Like here:
//Who is the MP for "Edinburgh South"
public static String qA(List<Seat> uk) {
for (Seat s : uk)
if (s.place.startsWith("Edinburgh South"))
return (s.mp);
return "Not found";
}
Now,instead of getting just the mp for Edinburgh South I need to get the vote values, compare them to each other, take the second biggest and display the associate party value.
Would appreciate any help, like how to access data from that Array would help me get started at least.
An element in an ArrayList is accesses by its index.
Seems you can just sort your ArrayList based on the vote values of the objects which are in the list.
For this you may want to look here: Sort ArrayList of custom Objects by property
Of course sorting is maybe too much for your given problem. Alternatively,
you may just iterate through the list and pick the two objects with the highest
votes values as you go.

For Each Loops and For Loops Java

I want to be able to create a for loop like this
For(each booking)
sounds simple for all you experts out there, but ive tried researching how to do this,
and its left me a little confused,
I assume id need a for each loop, which would be something like this
for (type var : coll) {
body-of-loop
}
This program creates a new booking and then allows the user to enter the details into the program of that booking, I have named this B1. IS it that value you enter into the for loop?
I know ill get rated down on this, but i dont understand how i get it to loop for each booking.
Thanks for the quick answers, Ive written some code which ill provide now. Hopefully it will make it easier to see.
Booking Class
public class Booking
{
private int bookingId;
private String route;
private double startTime;
private String bookingDate;
public Booking()
{
bookingId = 0000;
route = "No Route Entered";
startTime = 0.00;
bookingDate = "No Date entered";
}
public int getBookingId()
{
return bookingId;
}
public String getRoute()
{
return route;
}
public double getStartTime()
{
return startTime;
}
public String getBookingDate()
{
return bookingDate;
}
public void setBookingId(int bookingId)
{
this.bookingId = bookingId;
}
public void setRoute(String route)
{
this.route = route;
}
public void setStartTime(double startTime)
{
this.startTime = startTime;
}
public void setBookingDate(String bookingDate)
{
this.bookingDate = bookingDate;
}
public Booking(int bookingId, String route, double startTime, String bookingDate)
{
setBookingId(bookingId);
setRoute(route);
setStartTime(startTime);
setBookingDate(bookingDate);
}
public String toString()
{
return "BookingId: " + getBookingId() + "\nRoute: " + getRoute() + "\nStart Time: " + getStartTime() +
"\nBooking Date: " + getBookingDate();
}
}
Main Class
import java.util.*;
public class Main {
public static void main(String[] args) {
//<editor-fold defaultstate="collapsed" desc="Creates new Student and booking">
Student s1 = new Student();
Booking b1 = new Booking();
s1.setStudentId(Integer.parseInt(JOptionPane.showInputDialog("Enter ID for Student: [0001]")));
s1.setFname(JOptionPane.showInputDialog("Enter first name of Student: "));
s1.setLname(JOptionPane.showInputDialog("Enter last name of Student: "));
s1.setAddress(JOptionPane.showInputDialog("Enter address for Student: "));
s1.setPhoneNo(JOptionPane.showInputDialog("Enter phone number for Student: "));
s1.setOtherDetails(JOptionPane.showInputDialog("Enter other details for Student: [Glasses?]"));
b1.setBookingId(0002);
b1.setStartTime(Double.parseDouble(JOptionPane.showInputDialog("Enter Start time for Booking: [1200]")));
b1.setBookingDate(JOptionPane.showInputDialog("Enter Date for Booking: [01-JAN-12]"));
//</editor-fold>
//For Each Booking
}
}
}
List <Booking> allBookings = new ArrayList<Booking>();
//fill your AllBookings with data
for(Booking b:allBookings){
body of loop // b is your actual Booking Object
}
Something like this would do your work.
You will need an Booking Class, and some data stored in your AllBookings Array List. With you ensure that only Booking Objects can be placed within that Array List.
But back to the For each loop.
The first part (Booking) defines which Object-type is placed in
the list,array or what you want to compute through. Note: You could also place Object instead of Booking since everything is an Object, but I would not recommend you to do that.
The second one (b) is the name of the variable which stands for
the actual element in your list, when iterating over it.
And the third and final part (AllBookings) is your Collection or Array where all your Objects are placed in.
Java Documentation for For-Each Loops:
http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
You got the syntax right, you just need to pass a collection (or an array) of the objects to the loop:
// bookings is Booking[] or a collection of Booking objects, like List<Booking>
for (Booking b : bookings)
{
// do whatever you need to do with b
}
Type is the name of the type of your object: the thing you'd use to declare it. E.G. Booking.
var is the name of the placeholder variable, which will assume the value of each element that you loop over in the collection. This can be whatever you want.
coll is the name of the collection you want to loop over. It sounds like maybe you called this B1.
So you would use
for (Booking booking : B1){
//body
}
What is booking? foreach loops are used for Array Iteration
I'm assuming this is what you're trying to do, lets say booking is an array of type String[] (i can edit my answer if it's something else)
String[] booking = new String[]{"Hello", "How are You", "Goodbye"};
for (String s: booking)
{
System.out.println(s);
}
for (int i=0; i < booking.length; i++)
{
System.out.println(booking[i]);
}
Produces the following output:
Hello
How are You
Goodbye
Hello
How are You
Goodbye
If you have a collection of type Foo like this:
List<Foo> someList = getSomeList();
Then to loop you can do:
for(Foo myFoo : someList){
System.out.println("I have a foo : "+myFoo);
}
I don't fully understand what you're asking in the paragraph where you mention B1, as what you're describing doesn't seem to require looping at all.
But in general, the for-each loop works the way you've described. Note that the right hand variable is called coll - this is because it needs to be some sort of collection of elements (strictly something that implements Iterable). So if you have e.g. a List<Booking>, you could loop over all of the bookings in this list in turn as follows:
List<Booking> bookings = ...; // populated somehow, or passed in, whatever
for (Booking b : bookings) {
// Do what you want to b, it will be done in turn to each booking in the list
// For example, let's set the hypothetical last updated date to now
b.setLastUpdated(new Date());
}
// At this point all bookings in the list have had their lastUpdated set to now
Going back to what you described:
This program creates a new booking and then allows the user to enter the details into the program of that booking, I have named this B1.
It sounds like you have a booking. Are you sure you need a loop for just one booking? A loop involves performing the same actions on a bunch of different objects; what is it you want to loop over?

Categories

Resources