We will now look at updating the stored values in the Spot
fields.
Recall that:
Spot
are private.However, there is no mechanism / methods provided to update the instance fields. If we want to provide this functionality, we have to add the following methods ‘set’ methods to Spot
, one for each instance field:
public void setxCoord(float xCoord) {
this.xCoord = xCoord;
}
public void setyCoord(float yCoord) {
this.yCoord = yCoord;
}
public void setDiameter(float diameter) {
this.diameter = diameter;
}
Now Spot
is ready to update the contents of each of it’s fields; we just need to ask the user for the new value and update the contents with it.
Driver
changesIn Driver, we have several methods that allow us to:
We now need to add a method that will allow us to update the contents of the Spot
fields using the new ‘set’ methods we just added above.
Add the following method:
void updateSpotDetails(){
System.out.print("Enter new xCoord value: ");
float enteredXCoord = input.nextFloat();
System.out.print("Enter new yCoord value: ");
float enteredYCoord = input.nextFloat();
System.out.print("Enter new diameter value: ");
float enteredDiameter = input.nextFloat();
spot.setxCoord(enteredXCoord);
spot.setyCoord(enteredYCoord);
spot.setDiameter(enteredDiameter);
}
And then update the Driver()
constructor to call this new method and then redraw the spot (so we can see the new values):
Driver(){
addSpotDetails();
drawSpot();
printRadius();
printArea();
printCircumference();
//update spot details and redraw spot
updateSpotDetails();
drawSpot();
}
When you run the app, you should have output similar to this:
Save your work.