How do a reference a variable in another object - java

I am an absolute programming beginner, and I am trying to learn Java from a book. I'm very confused.
The book has an exercise (this is like halfway through the chapter, so there's a lot building up to this, but I'll try to make it clear) that asks us to add a method to a class. Basically, we were given a prebuilt set of classes that are supposed to be like a simple auction program. So there is an array list which contains a list of bidders, how much they bid, and the lot number. This exercise asks us to add a method that will print out a list of the names of the winning bidders and the value of their bids.
Okay, that makes sense. I can wrap my mind around how it is supposed to work. I even wrote the following code: `
/**
* Exercise 4.48
* for each item in the list of lots, get the highest bid.
* if highest bid is not null, print the bidder and value
* otherwise, print "lot not sold"
*/
public void close()
{
for(Lot lot : lots) {
Bid highestBid = lot.getHighestBid();
if(highestBid != null) {
System.out.println(bidder, value);
}
else{
System.out.println("Lot not sold.");
}
}
}
When try to compile it, it stops on bidder because I haven't defined the variable. So obviously I am supposed to tell it what "bidder" is supposed to mean. Bidder is the name of the variable in the "Person" object in the same program and is used throughout the project, but I'm still not clear on how to get it to understand that my "bidder" is the same "bidder." I assume that I will have the same issue with "value."
What am I missing?
Edited to make the code actually look like code.
As requested, here is the Person... class? (I'm not great with the terminology. I'll get there. Sorry.)
/**
* Maintain details of someone who participates in an auction.
* #author David J. Barnes and Michael Kölling.
* #version 2011.07.31
*/
public class Person
{
// The name of this person.
private final String name;
/**
* Create a new person with the given name.
* #param name The person's name.
*/
public Person(String name)
{
this.name = name;
}
/**
* #return The person's name.
*/
public String getName()
{
return name;
}
}
**/**
* A class to model an item (or set of items) in an
* auction: a lot.
*
* #author David J. Barnes and Michael Kölling.
* #version 2011.07.31
*/
public class Lot
{
// A unique identifying number.
private final int number;
// A description of the lot.
private String description;
// The current highest bid for this lot.
private Bid highestBid;
/**
* Construct a Lot, setting its number and description.
* #param number The lot number.
* #param description A description of this lot.
*/
public Lot(int number, String description)
{
this.number = number;
this.description = description;
this.highestBid = null;
}
/**
* Attempt to bid for this lot. A successful bid
* must have a value higher than any existing bid.
* #param bid A new bid.
* #return true if successful, false otherwise
*/
public boolean bidFor(Bid bid)
{
if(highestBid == null) {
// There is no previous bid.
highestBid = bid;
return true;
}
else if(bid.getValue() > highestBid.getValue()) {
// The bid is better than the previous one.
highestBid = bid;
return true;
}
else {
// The bid is not better.
return false;
}
}
/**
* #return A string representation of this lot's details.
*/
public String toString()
{
String details = number + ": " + description;
if(highestBid != null) {
details += " Bid: " +
highestBid.getValue();
}
else {
details += " (No bid)";
}
return details;
}
/**
* #return The lot's number.
*/
public int getNumber()
{
return number;
}
/**
* #return The lot's description.
*/
public String getDescription()
{
return description;
}
/**
* #return The highest bid for this lot.
* This could be null if there is
* no current bid.
*/
public Bid getHighestBid()
{
return highestBid;
}
}
**
/**
* A class that models an auction bid.
* It contains a reference to the Person bidding and the amount bid.
*
* #author David J. Barnes and Michael Kölling.
* #version 2011.07.31
*/
public class Bid
{
// The person making the bid.
private final Person bidder;
// The value of the bid. This could be a large number so
// the long type has been used.
private final long value;
/**
* Create a bid.
* #param bidder Who is bidding for the lot.
* #param value The value of the bid.
*/
public Bid(Person bidder, long value)
{
this.bidder = bidder;
this.value = value;
}
/**
* #return The bidder.
*/
public Person getBidder()
{
return bidder;
}
/**
* #return The value of the bid.
*/
public long getValue()
{
return value;
}
}
import java.util.ArrayList;
/**
* A simple model of an auction.
* The auction maintains a list of lots of arbitrary length.
*
* #author David J. Barnes and Michael Kölling.
* #version 2011.07.31
*
* 3/12/15 added close method exercise 4.48
*
*/
public class Auction
{
// The list of Lots in this auction.
private ArrayList<Lot> lots;
// The number that will be given to the next lot entered
// into this auction.
private int nextLotNumber;
/**
* Create a new auction.
*/
public Auction()
{
lots = new ArrayList<Lot>();
nextLotNumber = 1;
}
/**
* Enter a new lot into the auction.
* #param description A description of the lot.
*/
public void enterLot(String description)
{
lots.add(new Lot(nextLotNumber, description));
nextLotNumber++;
}
/**
* Show the full list of lots in this auction.
*/
public void showLots()
{
for(Lot lot : lots) {
System.out.println(lot.toString());
}
}
/**
* Make a bid for a lot.
* A message is printed indicating whether the bid is
* successful or not.
*
* #param lotNumber The lot being bid for.
* #param bidder The person bidding for the lot.
* #param value The value of the bid.
*/
public void makeABid(int lotNumber, Person bidder, long value)
{
Lot selectedLot = getLot(lotNumber);
if(selectedLot != null) {
Bid bid = new Bid(bidder, value);
boolean successful = selectedLot.bidFor(bid);
if(successful) {
System.out.println("The bid for lot number " +
lotNumber + " was successful.");
}
else {
// Report which bid is higher.
Bid highestBid = selectedLot.getHighestBid();
System.out.println("Lot number: " + lotNumber +
" already has a bid of: " +
highestBid.getValue());
}
}
}
/**
* Return the lot with the given number. Return null
* if a lot with this number does not exist.
* #param lotNumber The number of the lot to return.
*/
public Lot getLot(int lotNumber)
{
if((lotNumber >= 1) && (lotNumber < nextLotNumber)) {
// The number seems to be reasonable.
Lot selectedLot = lots.get(lotNumber - 1);
// Include a confidence check to be sure we have the
// right lot.
if(selectedLot.getNumber() != lotNumber) {
System.out.println("Internal error: Lot number " +
selectedLot.getNumber() +
" was returned instead of " +
lotNumber);
// Don't return an invalid lot.
selectedLot = null;
}
return selectedLot;
}
else {
System.out.println("Lot number: " + lotNumber +
" does not exist.");
return null;
}
}
/**
* Exercise 4.48
* for each item in the list of lots, get the highest bid.
* if highest bid is not null, print the bidder and value
* otherwise, print "lot not sold"
*/
public void close()
{
for(Lot lot : lots) {
Bid highestBid = lot.getHighestBid();
if(highestBid != null) {
System.out.println(bidder, value);
}
else{
System.out.println("Lot not sold.");
}
}
}

Thanks for clarifying your question by providing the supporting code!
This should fix your problem. Change this line:
System.out.println(bidder, value);
to this:
System.out.println(highestBid.getBidder().getName() + " bids " + highestBid.getValue())
The highestBid variable stores an object of type Bid. You can see the Bid class definition to see what it means for an object to have type Bid. Basically, a Bid object has a method called getValue(), which returns the value of the bid, and a method getBidder(), which returns a Person object (an object that abides by the Person class definition). So, look in the Person class and see how a Person object has a method called getName(), which returns the name of the person as a String.
Finally, we can just print the name and value with our handy built-in System.out.println() function.

To teach you the very basic,
Consider a class as a real life object,
It has it own characteristics which you define as class variables.
These should be (generally) defined private so a call to them has to happen from a class-function (getters and setters). The reason why we do this is so you can setup some restrictions. (like: "not higher than 3" or "must be min. 4 char. long" ...)
The class functions are like: small hidden classes within a Class they execute some code. Notice the "In", functions IN class. not the other way around. So the variables you create inside the functions are not known to the class, but the function knows the class-variables.
I would suspect in your case that you called to bidderand value:
Without use of getters if they are defined private outside the same class where your close() function is defined.
But really it is very hard for us to know what is wrong. Please provide us with the classof the close() function
EDIT:
the code for close()should be...
public void close()
{
for(Lot lot : lots) {
Bid highestBid = lot.getHighestBid();
if(highestBid != null) {
System.out.println(highestBid.getBidder(), highestBid.getValue());
}
else{
System.out.println("Lot not sold.");
}
}

Related

Should I use atomic integer or sync

I've got a little confused about using atomic/volatile/sync in my code.
Let's say I have an object of book info in a bookstore and for example, it may happen that two threads want to take the same book while the amount in the inventory is only 1, how can I promise that only one thread will take the book?
do I have to use synchronize?
BookInventoryInfo:
package bgu.spl.mics.application.passiveObjects;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Passive data-object representing a information about a certain book in the inventory.
*
* <p>
*
*/
public class BookInventoryInfo {
//The title of the book, his amount in the inventory and the price
private String bookTitle;
private AtomicInteger amountInInventory;
private int price;
public BookInventoryInfo(String bookTitle, int amountInInventory, int price) {
this.bookTitle = bookTitle;
this.price = price;
this.amountInInventory = new AtomicInteger(amountInInventory);
}
/**
* Retrieves the title of this book.
* <p>
* #return The title of this book.
*/
public String getBookTitle() {
return this.bookTitle;
}
/**
* Retrieves the amount of books of this type in the inventory.
* <p>
* #return amount of available books.
*/
public int getAmountInInventory() {
return this.amountInInventory.get();
}
/**
* Retrieves the price for book.
* <p>
* #return the price of the book.
*/
public int getPrice() {
return this.price;
}
public void reduceAmountInInventory() {
this.amountInInventory.decrementAndGet();
}
}
The way I want to take the book:
if(book.getAmountInInventory > 0)
{
book.amountInInventory--
}
You should use synchronized as using AtomicInteger isn't as simple as it might appear at first glance. While individual operations on AtomicInteger are thread safe, using multiple operations might not be. Your example is a good one. say you have
// say it start at 1
Thread1: if(book.getAmountInInventory > 0)
Thread2: if(book.getAmountInInventory > 0)
Thread1: book.amountInInventory--
Thread2: book.amountInInventory--
The amount is now -1.
If you use synchronized it is much simpler to hold the lock for the whole operation
synchronized (book) {
if(book.getAmountInInventory > 0) // no chance for a race condition here.
{
book.amountInInventory--
}
An AtomicInteger isn't sufficient here. While it would allow you to decrement the number of copies in the inventory atomically, that isn't enough - you don't need to just decrement it atomically, you also need to add some custom logic.
I'd use a plain old int, and protect its modification with explicit synchronized blocks or methods:
public class BookInventoryInfo {
private String bookTitle;
private int amountInInventory;
private int price;
public synchronized void checkOut() {
if (amountInInventory <= 0) {
throw new BookCheckoutException("No book in inventory");
}
amountInInventory--;
}
// All the other methods...
}
As an alternative to synchronization, you can also use a compareAndSet:
int a = book.amountInventory.get();
if (a > 0) {
boolean updated = book.amountInInventory.compareAndSet(a, a - 1);
}
This will only decrement the value of amountInInventory if its value is still a when you come to update it. The return value of compareAndSet indicates whether the value was changed or not.
You can wrap this in a loop, something like:
while (true) {
int a = book.amountInventory.get();
if (a == 0) {
return false; // To mean "no book in inventory";
}
if (book.amountInInventory.compareAndSet(a, a - 1)) {
return true; // To mean "there was a book in inventory, and it was removed".
}
}

Using DateTimeFormatter & LocalDateTime to retrieve day/month/year at hour/minute (Java 1.8)

is using DateTimeFormatter and LocalDateTime best for retrieving a previously set date? If so, how can I implement it into my code (below)?
Update on what I've managed to come up with so far. I think that I more or less know how the date is supposed to work but now I encountered another issue and I am not sure how to solve it so hopefully after posting the code here, I'll be able to get an answer to my problem. In short, I am not sure about a few requirements that I need to implement for my solution to the assignment to work. That's why I'll also post the full requirements below.
Requirements:
(In the comment below)
[u](Tests were left out as they can be dealt with later on.)[/u]
Code:
Model class [b](Everything to do with assignment was done by me and the rest was already provided)[/b]:
public class Model implements StudentModel {
private ArrayList<Student> students = new ArrayList<>();
private Student currentStudent = null;
private ArrayList<Module> modules = new ArrayList<>();
private Module currentModule;
private ArrayList<Enrolment> enrolments = new ArrayList<>();
private Enrolment currentEnrolment;
private ArrayList<Assignment> assignments = new ArrayList<>();
private Assignment currentAssignment = null;
/**
* This method is called when the "Add" button in the students data panel is clicked. The
* expectation is that the method will validate the data and if the data is valid create a
* new Students object. The method will then store the students object for later retrieval.
* #param number is the students identification number
* #param name of the students
* #param userId is the students userid / email
*/
#Override
public void addStudent(int number, String name, String userId) {
Student student = Student.createStudent(number, name, userId, this);
if (student != null && !foundStudent(student)) {
this.students.add(student);
setCurrentStudent(student);
}
}
/**
* This method is called when the "Modify" button in the student data panel is clicked. The
* expectation is that the method will validate the data and if the data is valid, it will
* modify the currently selected Student object. Since this is already in the collection,
* there is no need to do anything else.
* #param number is the student identification number
* #param name of the student
* #param userId is the students userid / email
*/
public void modifyStudent(int number, String name, String userId) {
if (currentStudent == null) {
setErrorMessage("No current student selected");
return;
}
Student student = Student.createStudent(number, name, userId, this);
if (student != null && (currentStudent.getNumber() == number || !foundStudent(student))) {
currentStudent.setNumber(number);
currentStudent.setName(name);
currentStudent.setUserId(userId);
}
}
/**
* This method is called when the "Find" button in the student data panel is clicked. The
* method should only use values from fields that have been entered. If an object is found
* then it should be set to the current object.
*
* #param number of student to be found
* #param name of student to be found
* #param userId is the students userid / email
* #return true if a student object is found
*/
public boolean findStudent(int number, String name, String userId) {
setErrorMessage("");
for (Student student: students) {
if ((number == 0 || number == student.getNumber()) &&
(name.equals("") || name.equals(student.getName()))) {
setCurrentStudent(student);
return true;
}
}
setErrorMessage("No student object found");
return false;
}
/**
* Determine whether the students or the students number already exists in the collection
*
* #param student object to be inserted
* #return true if duplicate students found or students number already used
*/
private boolean foundStudent(Student student) {
boolean duplicate = false;
for (Student student1 : students) {
if (student.equals(student1)) {
addErrorMessage("Student already in database");
duplicate = true;
} else if (student.getNumber() == student1.getNumber()) {
addErrorMessage("Student number already in database");
duplicate = true;
}
}
return duplicate;
}
/**
* This method is called when the user interface wants to know the size of the collection of
* students.
*
* #return an integer value representing the number of students in the collection.
*/
public int getNumberOfStudents() {
return students.size();
}
/**
* This method is called when the user interface wants to access members of the collection of
* Student objects. It provides an index of the item that it wants to retrieve.
*
* #param index of item to be retrieved
* #return a students object
*/
public Student getStudentAt(int index) {
return students.get(index);
}
/**
* This method is called when the user interface needs to be able to display
* information about the currently selected or entered students
*
* #return a string with the data for the currently selected students
*/
public Student getCurrentStudent() {
return currentStudent;
}
/**
* Retrieves the current student id
*
* #return the current student id
*/
public int getStudentNumber() {
return currentStudent.getNumber();
}
/**
* Retrieves the current student name
*
* #return the current student name
*/
public String getStudentName() {
return currentStudent.getName();
}
/**
* Retrieves the current student user id
*
* #return the current student user id
*/
public String getStudentUserId() {
return currentStudent.getUserId();
}
/**
* This method is called when the user selects a Student in the Student list.
*
* #param selectedStudent is reference to the currently selected students object.
*/
public void setCurrentStudent(Student selectedStudent) {
if (selectedStudent == null) {
addErrorMessage("This shouldn't be called with a null reference");
return;
}
enrolments = selectedStudent.getEnrolments();
currentEnrolment = null;
currentStudent = selectedStudent;
}
/**
* This method is called when the user clicks the "Delete" button on the Student panel. It
* should assume that the request is to delete the currently selected student.
*/
public void deleteStudent() {
if (currentStudent == null) {
setErrorMessage("No student selected to delete");
return;
}
currentStudent.deleteEnrolments();
students.remove(currentStudent);
clearStudent();
}
/**
* This method should clear the currently selected student.
*/
public void clearStudent() {
if (currentStudent != null && enrolments == currentStudent.getEnrolments()) {
enrolments = new ArrayList<>();
currentEnrolment = null;
}
currentStudent = null;
}
/**
* This method is called when the "Add" button in the currentModule data panel is clicked. The
* expectation is that the method will validate the data and if the data is valid create a
* new Module object. The method will then store the currentModule object for later retrieval.
*
* #param code of the currentModule
* #param name of the currentModule
* #param credits that the currentModule is worth.
*/
#Override
public void addModule(String code, String name, int credits) {
Module module = Module.createModule(code, name, credits, this);
if (module != null && !moduleFound(module)) {
modules.add(module);
setCurrentModule(module);
}
}
/**
* This method is called when the "Modify" button in the module data panel is clicked. The
* expectation is that the method will validate the data and if the data is valid modify the
* current Module object.
*
* #param code of the module
* #param name of the module
* #param credits that the module is worth.
*/
public void modifyModule(String code, String name, int credits) {
if (currentModule == null) {
setErrorMessage("No current module selected");
return;
}
Module module = Module.createModule(code, name, credits, this);
if (module != null && (currentModule.getCode().equals(code) || !moduleFound(module))) {
currentModule.setCode(code);
currentModule.setName(name);
currentModule.setCredits(credits);
}
}
/**
* This method is called when the "Find" button in the module data panel is clicked. The
* method should only use values from fields that have been entered. If an object is found
* then it should be set to the current object.
*
* #param code of the module
* #param name of the module
* #return true if a module was found and false otherwise
*/
public boolean findModule(String code, String name) {
setErrorMessage("");
for (Module module: modules) {
if ((code.equals("") || code.equals(module.getCode())) &&
(name.equals("") || name.equals(module.getName())) ||
(code.equals("") && name.equals(module.getName()))) {
setCurrentModule(module);
return true;
}
}
setErrorMessage("No matching module found");
return false;
}
/**
* Determine whether this would be a duplicate object or the module code already exists
*
* #param module object
* #return true if module already exists
*/
private boolean moduleFound(Module module) {
boolean found = false;
for (Module module1 : modules) {
if (module.equals(module1)) {
addErrorMessage("Module already on database");
found = true;
} else if (module.getCode().equals(module1.getCode())) {
addErrorMessage("Module code already on database");
found = true;
}
}
return found;
}
/**
* This method is called when the interface needs to know the size of the collection of modules.
*
* #return an integer value representing the number of elements in the collection
*/
public int getNumberOfModules() {
return modules.size();
}
/**
* This method is called when the user interface wants to access members of the collection of
* Module objects. It provides an index of the item that it wants to retrieve.
*
* #param index of item to be retrieved
* #return a Module object
*/
public Module getModuleAt(int index) {
return modules.get(index);
}
/**
* This method is called when the user clicks the "Delete" button on the Module panel. It
* should assume that the request is to delete the currently selected Module.
*/
public void deleteModule() {
if (currentModule == null) {
setErrorMessage("No module selected to delete");
return;
}
currentModule.deleteEnrolments();
modules.remove(currentModule);
clearModule();
}
/**
* This method should clear the currently selected module.
*/
public void clearModule() {
if (currentModule != null && enrolments == currentModule.getEnrolments()) {
enrolments = new ArrayList<>();
currentEnrolment = null;
}
currentModule = null;
}
/**
* This method is called when the user selects a Module in the Module list.
*
* #param selectedValue is a reference to the currently selected Module object.
*/
public void setCurrentModule(Module selectedValue) {
if (selectedValue == null) {
addErrorMessage("This shouldn't be called with a null reference");
return;
}
enrolments = selectedValue.getEnrolments();
currentEnrolment = null;
currentModule = selectedValue;
}
/**
* This method is called when the user interface needs to be able to display information
* about the currently selected or entered currentModule
*
* #return the current module
*/
public Module getCurrentModule() {
return currentModule;
}
/**
* Retrieves the current module code
*
* #return module code for currently selected module
*/
public String getModuleCode() {
return currentModule.getCode();
}
/**
* Retrieves the current module name
*
* #return module name for currently selected module
*/
public String getModuleName() {
return currentModule.getName();
}
/**
* Retrieves the current module credits
*
* #return module credits for currently selected module
*/
public int getModuleCredits() {
return currentModule.getCredits();
}
/**
* This method is called when the "Add" button in the currentEnrolment data panel is clicked. The
* expectation is that the method will validate the data and if the data is valid create a
* new Enrolment object. The method will then store the currentEnrolment object for later retrieval.
* <p/>
* The students and currentModule data should be those that are currently selected.
*
* #param year of currentEnrolment
* #param status of the currentEnrolment
* #param grade assigned for the currentModule.
*/
#Override
public void addEnrolment(int year, String status, int grade) {
Enrolment enrolment = Enrolment.createEnrolment(currentStudent, currentModule, year, status,
grade, this);
if (enrolment != null && !enrolmentFound(enrolment)) {
currentStudent.addEnrolment(enrolment);
currentModule.addEnrolment(enrolment);
currentEnrolment = enrolment;
}
}
/**
* This method is called when the "Modify" button in the enrolment data panel is clicked. The
* expectation is that the method will validate the data and if the data is valid modify the
* current Enrolment object.
* <p/>
* The student and module data should be those that are currently selected.
*
* #param year of enrolment
* #param status of the enrolment
* #param grade assigned for the module.
*/
public void modifyEnrolment(int year, String status, int grade) {
if (currentEnrolment == null) {
setErrorMessage("No current enrolment selected");
return;
}
Enrolment enrolment = Enrolment.createEnrolment(currentStudent, currentModule, year, status,
grade, this);
if (enrolment != null && (currentEnrolment.equals(enrolment) ||
!enrolmentFound(enrolment))) {
currentEnrolment.setStudent(currentStudent);
currentEnrolment.setModule(currentModule);
currentEnrolment.setYear(year);
currentEnrolment.setStatus(status);
currentEnrolment.setGrade(grade);
}
}
/**
* USed to find potentially duplicate modules
*
* #param enrolment object
* #return true if module object with similar values found
*/
private boolean enrolmentFound(Enrolment enrolment) {
for (Enrolment enrolment1 : enrolments) {
if (enrolment.equals(enrolment1)) {
addErrorMessage("Enrolment already in collection");
return true;
}
}
return false;
}
/**
* This method is called when the interface needs to know the size of the collection of
* enrolments.
*
* #return an integer value representing the number of elements in the collection
*/
public int getNumberOfEnrolments() {
return enrolments.size();
}
/**
* This method is called when the user interface wants to access members of the collection of
* Enrolment objects. It provides an index of the item that it wants to retrieve.
*
* #param index of item to be retrieved
* #return a Enrolment object
*/
public Enrolment getEnrolmentAt(int index) {
return enrolments.get(index);
}
/**
* Obtains the current enrolment
*
* #return the current enrolment
*/
public Enrolment getCurrentEnrolment() {
return currentEnrolment;
}
/**
* Retrieves the current enrolment year
*
* #return year for currently selected enrolment
*/
public int getEnrolmentYear() {
return currentEnrolment.getYear();
}
/**
* Retrieves the current enrolment status
*
* #return status for currently selected enrolment
*/
public String getEnrolmentStatus() {
return currentEnrolment.getStatus();
}
/**
* Retrieves the current enrolment grade
*
* #return grade for currently selected enrolment
*/
public int getEnrolmentGrade() {
return currentEnrolment.getGrade();
}
/**
* This method is called when the user clicks the "Delete" button on the Enrolment panel. It
* should assume that the request is to delete the currently selected Enrolment.
*/
public void deleteEnrolment() {
if (currentEnrolment == null) {
setErrorMessage("No enrolment selected to delete");
return;
}
currentEnrolment.delete();
currentEnrolment = null;
}
/**
* This method should clear the currently selected enrolment.
*/
public void clearEnrolment() {
currentEnrolment = null;
}
/**
* This method is called when the user selects an Enrolment in the Enrolment list.
*
* #param selectedValue is a reference to the currently selected Enrolment object.
*/
public void setCurrentEnrolment(Enrolment selectedValue) {
currentEnrolment = selectedValue;
currentStudent = currentEnrolment.getStudent();
currentModule = currentEnrolment.getModule();
}
/**
* This method is called when the "Add" button in the currentAssignment data panel is clicked. The
* expectation is that the method will validate the data and if the data is valid create a
* new Assignment object. The method will then store the currentAssignment object for later retrieval.
*
* #param title of the assignment
* #param moduleCode of the assignment
* #param dateTime is the date on which the assignment has to be handed in
* #param assignmentPercent weight of the assignment towards the final grade
*
*/
public void addAssignment(String title, String moduleCode, int assignmentPercent, LocalDateTime dateTime) {
Assignment assignment = Assignment.createAssignment(title, moduleCode, assignmentPercent, dateTime, this);
if (assignment != null && !foundAssignment(assignment)) {
this.assignments.add(assignment);
setCurrentAssignment(assignment);
}
}
/**
* This method is called when the "Modify" button in the Assignment data panel is clicked. The
* expectation is that the method will validate the data and if the data is valid, it will
* modify the currently selected Assignment object. Since this is already in the collection,
* there is no need to do anything else.
* #param title of the assignment by which it can be found
* #param moduleCode contains the module's code
* #param assignmentPercent weight of the assignment towards the final grade
*/
public void modifyAssignment(String title, String moduleCode, int assignmentPercent, LocalDateTime dateTime) {
if (currentAssignment == null) {
setErrorMessage("No current assignment selected");
return;
}
Assignment assignment = Assignment.createAssignment(title, moduleCode, assignmentPercent, dateTime, this );
if (assignment != null && (currentAssignment.getTitle() == title || !foundAssignment(assignment))) {
currentAssignment.setTitle(title);
currentAssignment.setModuleCode(moduleCode);
currentAssignment.setAssignmentPercent(assignmentPercent);
currentAssignment.setDueDate(dateTime);
}
}
/**
* This method is called when the "Find" button in the Assignment data panel is clicked. The
* method should only use values from fields that have been entered. If an object is found
* then it should be set to the current object 'currentAssignment'.
*
* #param title of the assignment by which it can be found
*/
public boolean findAssignment(String title) {
setErrorMessage("");
for (Assignment assignment: assignments) {
if (title.equals("") || title.equals(assignment.getTitle())){
setCurrentAssignment(assignment);
return true;
}
}
setErrorMessage("No assignment object found");
return false;
}
/**
* Determine whether the assignments or the assignment already exists in the database
*
* #param assignment object to be inserted
* #return true if duplicate assignments found or assignment number already used
*/
private boolean foundAssignment(Assignment assignment) {
boolean found = false;
for (Assignment assignment1 : assignments) {
if (assignment.equals(assignment1)) {
addErrorMessage("Assignment already in database");
found = true;
} else if (assignment.getTitle().equals(assignment1.getTitle())) {
addErrorMessage("Assignment title already in database");
found = true;
}
}
return found;
}
/**
* This method is called when the user selects an Assignment in the Assignment list.
*
* #param selectedValue is a reference to the currently selected Module object.
*/
public void setCurrentAssignment(Assignment selectedValue) {
if (selectedValue == null) {
addErrorMessage("This shouldn't be called with a null reference");
return;
}
// assignments = selectedValue.getAssignments();
// currentAssignments = null;
// currentAssignment = selectedValue;
}
/**
* This method is called when the user interface needs to be able to display information
* about the currently selected or entered currentAssignment
*
* #return the current assignment
*/
public Assignment getCurrentAssignment() {
return currentAssignment;
}
/**
* This method should clear the currently selected assignment.
*/
public void clearAssignment() {
currentAssignment = null;
}
/**
* Retrieves the current assignment title
*
* #return assignment title for currently selected assignment
*/
public String getAssignmentTitle() {
return currentAssignment.getTitle();
}
/**
* Retrieves the due date for the assignment
*
* #return the due date of the assignment
*/
public int getAssignmentDay() {
return dateTime.getDayOfMonth();
}
/**
* Retrieves the month on which the assignment has to be handed in
*
* #return due month for currently selected assignment
*/
public String getAssignmentMonth() {
return currentAssignment.getMonth();
}
/**
* Retrieves the year on which the assignment has to be handed in
*
* #return due year for currently selected assignment
*/
public String getAssignmentYear() {
return currentAssignment.getYear();
}
/**
* Retrieves the time on which the assignment has to be handed in
*
* #return due hour for currently selected assignment
*/
public String getAssignmentHour() {
return currentAssignment.getHour();
}
/**
* Retrieves the time on which the assignment has to be handed in
*
* #return due minutes for currently selected assignment
*/
public String getAssignmentMinute() {
return currentAssignment.getMins();
}
/**
* Retrieves the weight of the assignment towards the overall grade
*
* #return percentage weight for currently selected assignment
*/
public int getAssignmentPercent() {
return currentModule.getPercentage();
}
/*
* This block of code is the implementation for the Error Message interface.
*/
private String errorMessage = "";
/**
* This method simply replaces any message text currently stored with that passed in as a
* parameter. In effect, it clears past error messages and replaces them with the new message.
*
* #param errorMessage is the text of the message to be displayed
*/
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
/**
* This method appends the new message to the end of any existing error messages inserting
* the new line sequence between the existing error messages and the new message.
*
* #param errorMessage is the text of the message to be displayed
*/
public void addErrorMessage(String errorMessage) {
this.errorMessage += (this.errorMessage.length() == 0 ? "" : "\n") + errorMessage;
}
/**
* This method is called by the user interface when it wants to obtain the error messages that
* are to be displayed.
*
* #return the current stored error message
*/
public String getErrorMessage() {
return errorMessage;
}
}
My recommendation is to use LocalDateTime only to store the date and not each one of the separate fields that the date is composed of (i.e. day, month, etc.) since you can anytime extract and set all of them.
Using only LocalDateTime you can use both:
public void setDay(int day) {
dateTime.withDayOfMonth(day);
}
and
public int getDay() {
return dateTime.getOfMonth();
}
This will then allow you to remove all these fields:
private int day;
private int month;
private int year;
private int hour;
private int minute;
and have a much cleaner constructor:
public Assignment(String title, String moduleCode, int assignmentPercent, LocalDateTime dateTime) {
// ...
}
Homework?
For a homework assignment, your instructor may be looking for you to store each component (year, month, hour, and such) as separate numbers for instructional purposes, rather than using date-time classes.
In the real world, you certainly should be using the java.time framework.
Time Zone
And in a real world project, you should know that tracking a date-time without a time zone is asking for trouble.
Technically, a LocalDateTime has no time zone. A LocalDateTime actually has no meaning, and does not represent a moment on the timeline until you apply some timeline to give it meaning. You may assume an intended time zone for a LocalDateTime but that is risky and sloppy. That kind of assumption leads to problems later especially if there were any possible chance of this app later handling such data from another time zone or importing/exporting data from other sources that use other time zones.
UTC
The best practice for date-time work is to use UTC for your business logic, storage, and data exchange. Use a time in a specific time zone only as required such as presentation to a user.
To get to UTC, use your code as-is for parsing into a LocalDateTime. Then apply the time zone for which that value was implicitly assumed. Say, Québec. Apply that time zone, a ZoneId, to produce a ZonedDateTime. Finally, to get to UTC, ask that ZonedDateTime for an Instant.
You can think of it this way conceptually: ZonedDateTime = Instant + ZoneId
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = myLocalDateTime.atZone( zoneId );
From that extract an Instant, a moment on the timeline in UTC. Such Instant instances is what you should use for most business logic and data storage.
Instant instant = zdt.toInstant();
For presentation to a user later, apply the expected/desired time zone.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
Generating a Formatted String
Use your same formatter to generate a string. Or let java.time localize the format and language for you using a DateTimeFormatter. Specify a Locale which determines (a) the cultural norm for formatting a string, and (b) the translation of the name of day and of month into a particular human language.
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.LONG );
formatter = formatter.withLocale( Locale.CANADA_FRENCH );
String output = zdt.format( formatter );
Example Code
Put it all together.
String input = "29/04/2016 at 23:59";
DateTimeFormatter formatterForParsing = DateTimeFormatter.ofPattern ( "dd/MM/yyyy 'at' HH:mm" );
LocalDateTime ldt = LocalDateTime.parse ( input , formatterForParsing );
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime zdt = ldt.atZone ( zoneId );
Instant instant = zdt.toInstant ();
// Later, in other code, apply a time zone as required such as presentation to a user.
ZonedDateTime zdtForPresentation = ZonedDateTime.ofInstant ( instant , zoneId );
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime ( FormatStyle.LONG );
formatter = formatter.withLocale ( Locale.CANADA_FRENCH );
String output = zdtForPresentation.format ( formatter );
System.out.println ( "input: " + input + " | ldt: " + ldt + " | zdt: " + zdt + " | instant: " + instant + " | output: " + output );
input: 29/04/2016 at 23:59 | ldt: 2016-04-29T23:59 | zdt: 2016-04-29T23:59-04:00[America/Montreal] | instant: 2016-04-30T03:59:00Z | output: 29 avril 2016 23:59:00 EDT
Half-Open
Another issue… trying to define a due date by the last possible moment is the wrong approach.
In your case of 23:59, you are ignoring that a time-of-day can have a fractional second. In the old date-time classes, that means up to 3 digits of decimal places, 23:59.999. But some databases use microseconds, so 6 digits, 23:59.999999. And now in java.time and some other databases, nanoseconds for 9 digits, 23:59.999999999.
The better approach in date-time work is called Half-Open where the beginning is inclusive and the ending exclusive. So the due date-time is not the last moment of April 29 but the first moment of April 30. The assignment must be received before this first moment of that next day.
Just like your attendance in a class at 13:00 requires your derrière be in the seat before 1 PM.
So comparison logic is < rather than <=:
Boolean onTime = whenReceived.isBefore( whenDue );
Poof, your fractional second dilemma is gone.
To get that first moment of the next day, take your ZonedDateTime, add a day, convert to a LocalDate (a date-only value), call atStartOfDay while passing the same time zone again.
ZonedDateTime firstMomentOfNextDay = zdt.plusDays( 1 ).toLocalDate().atStartOfDay( zoneId );

Completing a constructor for an exact copy of a class in Java

I am working on a lab for school, the purpose is to go through a life insurance policy, and run tests to make sure my constructors are working properly. I have the regular constructors down, but I am confused about what is really needed in line 83. When I compile and submit my assignment, I get no information, except a pink highlight in that area. I tried creating a new policy object inserting...
WholeLifePolicy WholeLifePolicy2 = new WholeLifePolicy;
this is not what it wants.
}
/**
* Constructor for objects of class WholeLifePolicy.
* This constructor creates an exact copy of a
* WholeLifePolicy object.
*
* #param inPolicyObject WholeLifePolicy object.
*
*/
public WholeLifePolicy(WholeLifePolicy inPolicyObject)
{
this.setPolicyNum(inPolicyObject.getPolicyNum());
**// your code here, complete the constructor**
}
I also tried initializing instance variable from the WholeLifePolicy class, but I knew this wouldn't work since the copy takes on these parameters anyway.
I really just have no idea what to do. I have searched online and here, I keep getting information on clones, and dark copies. That is not what I am suppose to do. This is only the 6th week of my first programming class. I also contacted my teacher, but have not heard a reply yet.
public class WholeLifePolicy
{
// instance variables
private String policyNum;
private double faceValue;
private int policyYrs;
private String beneficiary;
// your code here - code the remaining 3 instance fields
// constants
/**
* surrender rate.
*/
public static final double SURRENDER_RATE = .65;
/**
* ADMINFEE.
*/
public static final double ADMINFEE = .005;
// constructors and methods
/**
* Constructor for objects of class WholeLifePolicy.
* This is the default constructor.
*
* Default values are:
* face value = 0.0
* policy years = 0
* policy number WLP9999999
* beneficiary Unknown
*
*/
public WholeLifePolicy()
{
this.setPolicyNum("WLP9999999");
this.setFaceValue(0.0);
this.setPolicyYrs(0);
this.setBeneficiary("Unknown");
}
/**
* Constructor for objects of class WholeLifePolicy.
* A policy number will be auto-generated.
*
* #param inPolicyNum Number of the policy
* #param inFaceValue Face Value of policy.
* #param inPolicyYrs Length of policy in years.
* #param inBeneficiary name of the beneficiary
*
*/
public WholeLifePolicy(String inPolicyNum, double inFaceValue,
int inPolicyYrs, String inBeneficiary)
{
// Initialize instance variables
// Using values passed in as parameters
this.policyNum = inPolicyNum;
this.faceValue = inFaceValue;
this.policyYrs = inPolicyYrs;
this.beneficiary = inBeneficiary;
*}
/
* Constructor for objects of class WholeLifePolicy.
* This constructor creates an exact copy of a
* WholeLifePolicy object.
*
* #param inPolicyObject WholeLifePolicy object.
*
*/
public WholeLifePolicy(WholeLifePolicy inPolicyObject)
{
this.setPolicyNum(inPolicyObject.getPolicyNum());
// your code here, complete the constructor
}***
/**
* Set the Policy Face Value.
*
* #param inFaceValue Face Value of policy.
*
*/
public void setFaceValue(double inFaceValue)
{
this.faceValue = inFaceValue;
}
/**
* Get the Policy Face Value.
*
* #return double Face Value of policy.
*
*/
public double getFaceValue()
{
return this.faceValue;
}
/**
* Set the Policy Years.
*
* #param inPolicyYrs Length of policy in years.
*
*/
public void setPolicyYrs(int inPolicyYrs)
{
this.policyYrs = inPolicyYrs;
}
/**
* Get the Policy Years.
*
* #return int Length of policy in years.
*
*/
public int getPolicyYrs()
{
return this.policyYrs;
}
/**
* Set the Policy Number. Use to override the default
* policy number or for copy object processing.
*
* #param inPolicyNum Policy Number.
*
*/
public void setPolicyNum(String inPolicyNum)
{
this.policyNum = inPolicyNum;
}
/**
* Get the Policy Number.
*
* #return String Policy Number.
*
*/
public String getPolicyNum()
{
// your code here, replace the following statement
return this.policyNum;
}
/**
* Set the beneficiary. Use to override the default
* beneficiary or for copy object processing.
*
* #param inBeneficiary Beneficiary to set up.
*
*/
public void setBeneficiary(String inBeneficiary)
{
this.beneficiary = inBeneficiary;
}
/**
* Get the Beneficiary.
*
* #return String Beneficiary.
*
*/
public String getBeneficiary()
{
// your code here, replace the following statement
return this.beneficiary;
}
/**
* Calculate surrender value.
* Surrender value is calculated as:
* (surrender rate * face value) *
* (years held / policy years) - amount borrowed -
* (face value * administrative fee)
*
* #param inYrsHeld Length in years policy held to date.
* #param inBorAmt Amount borrowed against policy if any.
* #return double Policy surrender value.
*
*/
public double surrenderVal(double inYrsHeld, double inBorAmt)
{
// Termination value is the surrender rate percentage of the face
// value as a proportion of the years held to policy years less any
// amount borrowed on the policy less a ADMINFEE on the
// face value.
// your code here, compute the surrender value and replace the
// following line
return (SURRENDER_RATE * faceValue) * (inYrsHeld) / (policyYrs)
- inBorAmt - (faceValue * ADMINFEE);
}
/**
* Return a string representation of the WholeLifePolicy.
*
* #return String output string.
*
* <pre>
* Produce output in the following format:
*
* Policy Information:
* Policy #: WLP1000000
* Policy Years: 20
* Face Value: 50000.0
* Beneficiary: John Doe
*
* </pre>
*/
public String toString()
{
String output = "Policy Information:\n";
output = output + "Policy #: " + this.getPolicyNum() + "\n";
// your code here, finish the output string
return output;
}
}
HERE IS THE TEST CLASS, JUST IN CASE.
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* The test class WholeLifePolicyTest.
*
* #author Tina & edited by Jeremy
* #version Fall 2015
*/
public class WholeLifePolicyTest
{
/**
* Default constructor for test class WholeLifePolicyTest.
*/
public WholeLifePolicyTest()
{
// not used
}
/**
* Sets up the test fixture.
*
* Called before every test case method.
*/
#Before
public void setUp()
{
// not used
}
/**
* Tears down the test fixture.
*
* Called after every test case method.
*/
#After
public void tearDown()
{
// not used
}
/**
* Test empty (default) constructor #1.
*/
#Test
public void testConstructor1()
{
WholeLifePolicy policy = new WholeLifePolicy();
// verify an object reference was created
assertNotNull(policy);
// verify policy number is not null
assertEquals("WLP9999999", policy.getPolicyNum());
// verify face value set to default values
assertEquals(0.0, policy.getFaceValue(), .001);
// verify policy years set to default values
assertEquals(0, policy.getPolicyYrs());
// verify beneficiary is Unknown
assertEquals("Unknown", policy.getBeneficiary());
}
/**
* Test explicit constructor #2 (policy#, face value, years, name).
*/
#Test
public void testConstructor2()
{
// we test passing in values greater than zero only
String pnum = "WLP1234567";
double value = 50000.0;
int years = 20;
String name = "Paul Young";
WholeLifePolicy policy = new WholeLifePolicy(pnum, value, years, name);
// your code here, verify the object exists and the instance
// fields contain the expected values
assertEquals("WLP1234567", policy.getPolicyNum());
assertEquals(50000.0, policy.getFaceValue(), .001);
assertEquals(20, policy.getPolicyYrs());
assertEquals("Paul Young", policy.getBeneficiary());
}
/**
* Test explicit constructor #3 (duplicate object).
*/
#Test
public void testConstructor3()
{
// we test passing in values greater than zero only
String pnum = "WLP1234567";
double value = 50000.0;
int years = 20;
String name = "Paul Young";
WholeLifePolicy policy1 = new WholeLifePolicy(pnum, value, years, name);
// your code here, verify the object exists and the instance
// fields contain the expected values
assertEquals("WLP1234567", policy1.getPolicyNum());
assertEquals(50000.0, policy1.getFaceValue(), .001);
assertEquals(20, policy1.getPolicyYrs());
assertEquals("Paul Young", policy1.getBeneficiary());
}
/**
* Test the setGetFaceValue method.
*/
#Test
public void testSetGetFaceValue()
{
// test passing in values greater than zero only
double value = 75000.0;
WholeLifePolicy policy = new WholeLifePolicy();
policy.setFaceValue(value);
assertEquals(value, policy.getFaceValue(), .0001);
}
/**
* Test the setGetPolicyYrs method.
*/
#Test
public void testSetGetPolicyYrs()
{
// your code goes here, test the set and get methods for the
// policy years methods
int years = 25;
WholeLifePolicy policy = new WholeLifePolicy();
policy.setPolicyYrs(years);
assertEquals(years, policy.getPolicyYrs());
}
/**
* Test the SetGetPolicyNum method.
*/
#Test
public void testSetGetPolicyNum()
{
// your code goes here, test the set and get methods for the
// policy number methods
String policyNumber = "WLP7654321";
WholeLifePolicy policy = new WholeLifePolicy();
policy.setPolicyNum(policyNumber);
assertEquals(policyNumber, policy.getPolicyNum());
}
/**
* Test the SetGetBeneficiary method.
*/
#Test
public void testSetGetBeneficiary()
{
// your code goes here, test the set and get methods for the
// beneficiary methods
String benefactor = "Beetlejuice! Beetlejuice!";
WholeLifePolicy policy = new WholeLifePolicy();
policy.setBeneficiary(benefactor);
assertEquals(benefactor, policy.getBeneficiary());
}
/**
* Test the surrenderVal method.
*/
#Test
public void testSurrenderVal()
{
// we test passing in values greater than zero only
String num = "WLP1234567";
double value = 50000.0;
int years = 20;
String name = "Elton John";
double yearsHeld = 15.5;
double amtBorrowed = 10000.00;
WholeLifePolicy policy = new WholeLifePolicy(num, value, years, name);
double surVal = policy.surrenderVal(yearsHeld, amtBorrowed);
// your code here, test to make sure the returned surrender value
// is what was expected
assertEquals(surVal, 14937.5, .001);
//your code here, test to make sure the returned surrender value
// is what is expected if the borrowed amount is 0
double surVal2 = policy.surrenderVal(yearsHeld, 0);
assertEquals(surVal2, 24937.5, .001);
}
/**
* Test the toString method.
*/
#Test
public void testToString()
{
String num = "WLP1234567";
double value = 50000.0;
int years = 20;
String name = "Katie Perry";
WholeLifePolicy policy = new WholeLifePolicy(num, value, years, name);
String text = policy.toString();
assertTrue(text.contains("Policy Information:"));
assertTrue(text.contains("Policy #:"));
assertTrue(text.contains(num));
// your code here, finish the testing of the toString() method
// checking for both the headings and face value, policy years
}
}
Complete the constructor properly here
public WholeLifePolicy(WholeLifePolicy inPolicyObject)
{
//this.setPolicyNum(inPolicyObject.getPolicyNum());
/* **your code here, complete the constructor** */
this.policyNum = inPolicyObject.policyNum;
this.faceValue = inPolicyObject.faceValue;
this.policyYrs = inPolicyObject.policyYrs;
this.beneficiary = inPolicyObject.beneficiary;
}
And somewhere else in your code,
WholeLifePolicy inPolicyObject = new WholeLifePolicy(policyNum,faceValue,policyYrs,benificiary);
WholeLifePolicy WholeLifePolicy2 = new WholeLifePolicy(inPolicyObject);
If you want to keep exact copy in other object, just remove setter methods of each attributes. Only constructor will set the attributes.

Adding elements to an hashmap

So I have an issue with Hashmaps and a login feature.
When using addLogin I am required to enter parameters but it makes no sense to do this since I have already done this in the constructor classes. How would I simply just use addLogin and the Surname, Forename and Personal ID number is added to the hashmap?
Upon using Math.round(Math.random()*999+1) to generate a random number between 1-999 how am I supposed to go around adding this to the hashmap with the other student details?
Here is the full code that applies to both questions, apologies for the stupid questions I'm very new to Java! I am very appreciative of any help I recieve. Thanks in advance.
public class TestApplication
{
// hashmap
private HashMap<String, ArrayList <String>> Application = new HashMap<String, ArrayList <String>>();
// hashset
private HashSet<String> loginsIssued = new HashSet<String>();
// An Arry List for storing student information
private ArrayList<String> Student = new ArrayList<String>();
/**
* Constructor for objects of class Application
*/
public TestApplication(String Surname, String personalIdNo)
{
if (isValidpersonalIdNo(personalIdNo) == true)
{
Student.add(Surname);
Application.put(personalIdNo, Student);
System.out.println("Application number ### " + "has registered successfully");
}
else
{
System.out.println("Application has failed, Personal id: " + personalIdNo);
}
}
/**
* Create a Student Information
*/
public void TestApplication(String personalIdNo, String Surname, String Forename)
{
Student.add(Surname);
Student.add(Forename);
Student.add (personalIdNo);
}
/**
* Add Login
* Pull First Letter of Forenames
* Pull First Letter of Surname
* Generate Random Number
* Print
*/
public void addLogin(String Surname, String Forename)
{
String login = "";
{
System.out.println (Surname.charAt(0) + "" + " " + Forename.charAt(0) + " " + Math.round(Math.random()*999+1));
Student.add(login);
loginsIssued.add(login);
}
}
/**
* CONDITION 1
* Check whether the ID supplied is only numbers
*/
public boolean isNumeric(String personalIdNo)
{
if (personalIdNo.matches("((-|\\+)?[0-9]+(\\.[0-9]+)?)+")) {
return true;
}
else
{
return false;
}
}
/**
* CONDITION 2
* Check whether the ID supplied has a length of 10
*/
public boolean checkLength(String personalIdNo)
{
if (String.valueOf(personalIdNo).length()==10)
{
return true;
}
else
{
return false;
}
}
/**
* CONDITION 3
* Check whether the ID supplied starts with 1
*/
public boolean checkFirstDigit(String personalIdNo)
{
if (personalIdNo.startsWith("1"))
{
return true;
}
else
{
return false;
}
}
/**
* Validation Check - Check if it satisfies all conditions.
*/
public boolean isValidpersonalIdNo(String personalIdNo)
{
if (isNumeric(personalIdNo) && checkLength(personalIdNo) && checkFirstDigit(personalIdNo))
{
return true;
}
else
{
return false;
}
}
/**
* FORENAME
* Add Forename
*/
public void addForename(String Forename)
{
Student.add(Forename);
}
/**
* Return Surname
*/
public String getSurname()
{
return Student.get(0);
}
}
Concerning to your first question
At the initialisation i guess you just want to give the string a value normally you achieve this through writing
String login= null;
But I'm quiet not sure what you want to achieve with the empty ""
And i dont get why you dont give your login a value before you add it to the arraylist or should be this the login by default
public void addLogin(String Surname, String Forename)
String login = null;
{
System.out.println (Surname.charAt(0) + "" + " " + Forename.charAt(0) + " " + Math.round(Math.random()*999+1));
Student.add(login);
loginsIssued.add(login);
}
And just as a tip if you return boolean at your equalization methods you dont need to check in the if clauses if true == true because the if clause checks if you do it your way wether true ==true and returns true if it like this do you get my point? you 'll save resources if you dont do this twice :)
So just write your method which returns the boolean value in the if braces .
I hope i can help you
Pls comment if you need further informations
To be honest, I think there should be some rework to fix your code (sorry to not answer directly to you two questions but is impossible as is):
Fix the second constructor, which is declared as a method
Create a Student class: it is harder to retrieve fields by index and the risk is to add twice the same field or to miss adding one field.
Unless I don't fully understand what your code should achieve, the major issue is a design error : your TestApplication class manages the whole set of students and their login thus the Student instance variable is a nonsense as well as the constructors with a single student fields. You should instead create an addStudent method with the student fields as parameter or better a Student instance.
I don't understand the use of "" + " " either.
By consequence, to answer to your questions:
You can keep your addLogin method and if so, yes you have to keep all the info but you can use a Student object (or a Collection as you currently modelise a student) as parameter.
If you update the same Student (same object instance), it is of course updated in your map. If not(you use a copy of Student) then just execute Application.put(personId,Student). Have a look at this answer to get more info

Iterator and printing details

Hey all. I've been asked to create a method that uses an iterator to print details of 'lots'. I'm able to create an iterator that prints all of the details, however, for any lots that haven't been bought, a message should print out this fact and I'm unsure how I can add that code in. It is the public void close method I'm focusing on. This is what I have so far. Help is greatly appreciated.
public class Auction{
// The list of Lots in this auction.
private final ArrayList<Lot> lots;
// The number that will be given to the next lot entered
// into this auction.
private int nextLotNumber;
/**
* Create a new auction.
*/
public Auction(){
lots = new ArrayList<Lot>();
nextLotNumber = 1;
}
/**
* Enter a new lot into the auction.
*
* #param description
* A description of the lot.
*/
public void enterLot(final String description){
lots.add(new Lot(nextLotNumber, description));
nextLotNumber++;
}
/**
* Show the full list of lots in this auction.
*/
public void showLots(){
for(final Lot lot : lots){
System.out.println(lot.toString());
}
}
public void close(){
final Iterator<Lot> it = lots.iterator();
while(it.hasNext()){
}
}
/**
* Bid for a lot. A message indicating whether the bid is
* successful or not is printed.
*
* #param number
* The lot number being bid for.
* #param bidder
* The person bidding for the lot.
* #param value
* The value of the bid.
*/
public void bidFor(final int lotNumber,
final Person bidder,
final long value){
final Lot selectedLot = getLot(lotNumber);
if(selectedLot != null){
final boolean successful =
selectedLot.bidFor(new Bid(bidder, value));
if(successful){
System.out.println("The bid for lot number " + lotNumber
+ " was successful.");
} else{
// Report which bid is higher.
final Bid highestBid = selectedLot.getHighestBid();
System.out.println("Lot number: " + lotNumber
+ " already has a bid of: " + highestBid.getValue());
}
}
}
}
Does the Lot class have a flag indicating if it's purchased or not? If so then
for(final Lot lot : lots){
if (!lot.purchased) {
System.out.println("not bought");
}
}
BTW - I noticed you're using the pre for-each style iterator in the close method. There's no reason to do this since you'll have access to individual Lot instances in the for-each also.
I would add the information you want the Lot to print to the Lot.toString() I would suggest your close() method should close() each lot, and the lot should print anything which needs to be printed.
Add an attribute to the Lot class of type Person called "winner" or something similar.
In the bidFor method, in the if (successful) block, set the winner attribute:
selectedLot.setWinner(bidder);
Then when iterating through the lots, if the winner attribute is null, print your message that the lot hasn't been bought.
Or you could use:
if (lot.getHighestBid() == null)
depending on how the Lot class is implemented, hard to know without seeing the Lot class.

Categories

Resources