Issue with getter and setter with one common variable - java

I have a task with a temperature converter program. I have to use one veriable in a class what is used by two setter and two getter method.
This is the main class:
public class Main {
public static void main(String[] args) {
Homero ho = new Homero();
ho.setCelsius(0);
System.out.println(ho.getFahrenheit());
System.out.println(ho.getCelsius());
ho.setFahrenheit(212);
System.out.println(ho.getFahrenheit());
System.out.println(ho.getCelsius());
}
}
How can I say to the getters that when the main function set the first setter, the getter return with this... and in the second time return with that...
This is the Homero class:
public class Homero {
double celsius;
public void setCelsius(double celsius){
this.celsius = celsius;
}
public void setFahrenheit(double fahr){
this.celsius = fahr;
}
public double getFahrenheit(){
return (this.celsius*9)/5+32;
}
public double getCelsius(){
return (this.celsius-32)*5/9;
}
}
And this would be the proper output:
32.0
0.0
212.0
100.0
And the wrong output what I've got.
32.0
-17.77777777777778
413.6
100.0

The getter and setter for celsius does not need a conversion. Do your calculations in the getter and setter for fahrenheit:
public void setCelsius(double celsius){
this.celsius = celsius;
}
public void setFahrenheit(double fahr){
this.celsius = (fahr -32)*5/9;
}
public double getFahrenheit(){
return this.celsius*9/5+32;
}
public double getCelsius(){
return this.celsius;
}

I would suggest to reset the other value by the setters, so every time you set a value the other is also new calculated:
public static class Homero {
double celsius;
double fahrenheit;
public void setCelsius(double celsius) {
this.celsius = celsius;
this.fahrenheit = this.celsius * 1.8 + 32;
}
public void setFahrenheit(double fahr) {
this.fahrenheit = fahr;
this.celsius = (this.fahrenheit - 32) * 5 / 9;
}
public double getFahrenheit() {
return this.fahrenheit;
}
public double getCelsius() {
return this.celsius;
}
}

public void setFahrenheit(double fahr){
this.celsius = fahr;
}
this is worng you should convert fahr to cel before assignement.
here :
public double getCelsius(){
return (this.celsius-32)*5/9;
}
you should return this.celcius

Related

How do I get private instance variables into another class via inheritance (extends)?

I'm trying my hand at inheritance for the first time and I'm having difficulty wrapping my head around this.
Basically I have a Customer class and a WarrantyCustomer class. WarrantyCustomer says that the customer has a warranty and should be given a discount.
My Customer looks like this (not the whole class)
public class Customer {
private int monthsSinceVisit;
private double totalVisitCost;
(public constructor is here)
public int getMonthsSinceVisit(){
return monthsSinceVisit;
}
public double getTotalVisitCost(){
return totalVisitCost;
}
public double getNextVisitCost(){
totalVisitCost = 20.00 + (12.00*monthsSinceVisit);
return totalVisitCost;
}
}
And then in WarrantyCustomer I have:
public class WarrantyCustomer extends Customer {
private int monthsSinceDiscount;
#Override
public int getMonthsSinceVisit(){
return super.getMonthsSinceVisit();
}
#Override
public double getTotalVisitCost(){
return super.getTotalVisitCost();
}
(public constructor is here)
#Override
public double getNextVisitCost(){
while (monthsSinceDiscount>=12){
totalVisitCost = ((20.00 + (12.00*monthsSinceVisit)) * 0.20);
monthsSinceDiscount = 0;
}
return totalVisitCost;
}
}
I am unsure of why in my getNextVisitCost() in WarrantyCustomer it tells me that totalVisitCost and monthsSinceVisit are private in Customer. I know they are private but I thought I brought them into this class with my getter methods.
Thank you for any help. For this I am not permitted to set my instance variable to public or protected.
for this problem you should define a setter for your totalVisitCost and then access it in subclass:
public class Customer {
private int monthsSinceVisit;
private double totalVisitCost;
public int getMonthsSinceVisit(){
return monthsSinceVisit;
}
public double getTotalVisitCost(){
return totalVisitCost;
}
protected void setTotalVisitCost(double totalVisitCost) {
this.totalVisitCost = totalVisitCost;
}
public double getNextVisitCost(){
totalVisitCost = 20.00 + (12.00*monthsSinceVisit);
return totalVisitCost;
}
}
public class WarrantyCustomer extends Customer {
private int monthsSinceDiscount;
#Override
public int getMonthsSinceVisit(){
return super.getMonthsSinceVisit();
}
#Override
public double getTotalVisitCost(){
return super.getTotalVisitCost();
}
#Override
public double getNextVisitCost(){
while (monthsSinceDiscount>=12){
setTotalVisitCost(((20.00 + (12.00*getMonthsSinceVisit())) * 0.20));
monthsSinceDiscount = 0;
}
return getTotalVisitCost();
}
}
Since WarrantyCustomer is already inheriting the getters and setters from Customer and you don't need to modify them, you don't need to override them.
But the problem was you were trying to set the value of the totalVisitCost directly, instead of creating a setter and using it in the child class.
public class Customer {
private int monthsSinceVisit;
private double totalVisitCost;
// (public constructor is here)
public int getMonthsSinceVisit(){
return monthsSinceVisit;
}
public double getTotalVisitCost(){
return totalVisitCost;
}
// public setter for the private totalVisitCost
public void setTotalVisitCost(double cost) {
totalVisitCost = cost;
}
public double getNextVisitCost(){
totalVisitCost = 20.00 + (12.00*monthsSinceVisit);
return totalVisitCost;
}
}
public class WarrantyCustomer extends Customer {
private int monthsSinceDiscount;
// Don't need these overrides, it's already inherited.
// #Override
// public int getMonthsSinceVisit(){
// return super.getMonthsSinceVisit();
// }
// #Override
// public double getTotalVisitCost(){
// return super.getTotalVisitCost();
// }
#Override
public double getNextVisitCost(){
while (monthsSinceDiscount>=12){
// use the inherited setter and getter
setTotalVisitCost(((20.00 + (12.00*getMonthsSinceVisit())) * 0.20));
monthsSinceDiscount = 0;
}
return getTotalVisitCost();
}
}

Java: How to get the Average Area from the given shape

I'm writing a Java Program in which I have to get the Average Area from the given shape. I'm needing to get the average area from the askAreaProblem problem and here is the methods for the askAreaProblem and the getAverageArea method. The askAreaProblem method works fine, but the unit test for the getAverageArea method are failing. Here is my code for the two methods.
public class Assignment9 {
public static void askAreaProblem(IShape s, double acceptableVariance)
{
System.out.println("What is the area of a "+s.forProblemStatement());
double answer=new Scanner(System.in).nextDouble();
double area=s.getArea();
if(Math.abs(answer-area)<=acceptableVariance) {
System.out.println("Yay ! your answer, "+answer+" is correct");
} else {
System.out.println("Sorry :( your answer, "+answer+" is not correct.");
System.out.println("The correct answer is "+area);
}
}
public static double getAverageArea(IShape[] shapes)
{
double sum = 0;
double avg = sum/shapes.length;
for(IShape shape: shapes) {
sum += shape.getArea();
}
return avg;
}
Here is the Unit test. If it passes I get 20 points.
public void testAverageArea()
{
IShape[] shapes={new Rectangle(2,3), new Circle(1)};
Assert.assertEquals(4.57,Assignment9.getAverageArea(shapes),0.01);
IShape[] shapes2={new Rectangle(2,3)};
Assert.assertEquals(6,Assignment9.getAverageArea(shapes2),0.01);
}
#Grade(points=20)
#Test
Here is the rest of my code for the program that I'm writing:
package assignment;
import java.util.Scanner;
import java.util.Random;
interface IShape {
double getArea();
double getPerimeter();
String forProblemStatement();
}
class Rectangle implements IShape {
private double width, height;
public Rectangle(double width, double height) {
this.width=width;
this.height=height;
}
#Override
public double getArea() { return width*height; }
#Override
public double getPerimeter() { return 2*(width+height); }
#Override
public String toString(){ return "Rectangle[width:"+width+" height:"+height+"]"; }
#Override
public String forProblemStatement() {
return "rectangle with width "+ width +" and height "+height+".";
}
}
class Circle implements IShape {
private double radius;
public Circle(double radius) {
this.radius=radius;
}
#Override public double getArea() { return Math.PI*radius*radius;}
#Override public double getPerimeter() {return 2*radius*Math.PI;}
#Override public String toString(){ return "Circle[radius:"+radius+"]"; }
#Override public String forProblemStatement() {
return "circle with radius "+radius;
}
}
class Square implements IShape {
private double side;
public Square(double side) {
this.side=side;
}
double getSide(){return side;}
#Override
public double getArea() { return side * side; }
#Override
public double getPerimeter() { return 4 * side; }
#Override
public String toString(){ return "Square"; }
#Override
public String forProblemStatement() {
return "square.";
}
}
class RegularPolygon implements IShape {
private double sides;
private double size;
private double apothem;
public RegularPolygon(double sides, double size, double apothem) {
this.sides=sides;
this.size=size;
this.apothem=apothem;
}
double getSides(){
return sides;
}
#Override
public double getArea() {
return .5 * apothem * size * sides;
}
#Override
public double getPerimeter() {
return size * sides;
}
#Override
public String toString() {
return "RegularPolygon";
}
#Override
public String forProblemStatement() {
return "RegularPolygon";
}
}
class ShapeFactory {
public static Random randomGenerator=new Random();
public static IShape getShapeInstance(String kindOfShape, double param1, double param2, double param3) {
kindOfShape=kindOfShape.toLowerCase();
if(kindOfShape.equals("circle")) {
return new Circle(param1);
} else if (kindOfShape.equals("rectangle")) {
return new Rectangle(param1, param2);
}
else if (kindOfShape.equals("square")) {
return new Square(param1);
} else if (kindOfShape.equals("RegularPolygon")) {
return new RegularPolygon(param1, param2, param3);
}
return null;
}
public static IShape getRandomShape() {
String[] shapeNames={"circle", "rectangle", "square","RegularPolygon"};
int shape=randomGenerator.nextInt(shapeNames.length);
int param1=randomGenerator.nextInt(10)+1;
int param2=randomGenerator.nextInt(10)+1;
int param3=randomGenerator.nextInt(10)+1;
return getShapeInstance(shapeNames[shape],param1,param2,param3);
}
}
The computation of avg = sum/shapes.length should be after the loop of accumulating sum, not before.
Look at your code line by line.
First line you have declared sum with the value of zero.
Second line you have declared avg with value of sum/shapes.length.
This means avg will equal to zero, your getAverageArea method therefore will always return zero.
I suggest:
public static double getAverageArea(IShape[] shapes)
{
double sum = 0;
for(IShape shape: shapes) {
sum += shape.getArea();
}
return sum/shapes.length;
}

I am trying to figure out why my class payroll is not adding all the salaries properly....help me find the bug

So I am working on this Payroll class, I need to create two employees, hours worked and hourly pay and the calculate salaries. Finally, I have to add 10 extra hours to one of the previously created employees and calculate and display the total payroll. I wrote the two classes and everything works perfect, but when I look at the total Payroll it does not take into consideration the added hours.
The output for totalPayRoll should be $2000 after increasing the hours but i still get $1750!
public class PayRoll {
static double getTotalPayRoll()
{
return TotalPayRoll;
}
public String employeeId;
public int hoursWorked;
public final double hourlyPay;
private static double TotalPayRoll;
private static double Salary;
public PayRoll (String theEmployeeId, int theHoursWorked,
double theHourlyPay)
{
this.employeeId = theEmployeeId;
this.hoursWorked = theHoursWorked;
this.hourlyPay = theHourlyPay;
Salary = hoursWorked*hourlyPay;
TotalPayRoll = TotalPayRoll + Salary ;
}
public String getTheEmployeeId()
{
return this.employeeId;
}
public int getTheHoursWorked()
{
return this.hoursWorked;
}
public double getTheHourlyPay()
{
return this.hourlyPay;
}
public double getSalary()
{
return PayRoll.Salary;
}
public void increase (int extraHours)
{
hoursWorked = (hoursWorked + extraHours);
}
public void changeTheHoursWorked (int amount)
{
hoursWorked = hoursWorked + amount;
}
public void calculateSalary()
{
Salary = hoursWorked*hourlyPay;
}
public void calculateTotalPayRoll()
{
TotalPayRoll= TotalPayRoll+Salary;
}
public void changeHours(int newHours)
{
hoursWorked = newHours;
}
}
And this is the main
public class Test {
public static void main(String[] args) {
// TODO code application logic here
Date d = new Date();
DateFormat df = DateFormat.getDateInstance( DateFormat.MEDIUM );
NumberFormat nf = NumberFormat.getCurrencyInstance();
System.out.println("\nPayroll For Week Ending " + df.format(d));
System.out.println("-------------------------------------");
PayRoll employee1 = new PayRoll("444-4444", 30, 25);
employee1.calculateSalary();
displaySalary(employee1, nf);
PayRoll employee2 = new PayRoll("555-5555", 20, 50);
employee2.calculateSalary();
displaySalary(employee2, nf);
System.out.println("Increase " + employee1.getTheEmployeeId() +
" by 10 hours");
employee1.changeTheHoursWorked(10); // 10 hours increase
employee1.calculateSalary();
displaySalary(employee1, nf);
System.out.println("Total payout amount.. " +
nf.format(PayRoll.getTotalPayRoll()));
}
public static void displaySalary(PayRoll e, NumberFormat nf)
{
System.out.println("Employee #: " + e.getTheEmployeeId());
System.out.println("Hours Worked: " + e.getTheHoursWorked());
System.out.println("Hourly Rate: " + e.getTheHourlyPay());
System.out.println("Your Salary is: " + e.getSalary());
System.out.println("---------------------------------\n");
}
}
In your class :
private static double TotalPayRoll;
private static double Salary;
Both are static members(class level members), so there will be only one copy of these members which will be shared among all the objects. Because TotalPayRoll and salary should be different for different payrolls so these should be non-static.
This is because you have static fields - make everything non-static
private static double TotalPayRoll; -> private double TotalPayRoll;
private static double Salary; -> private double Salary;
What is happening with static fields is
Firstly hoursWorked is set to 30
then
hoursWorked is set to 20
then
hoursWorked is increased by 10
Since you are declaring objects of your PayRoll class, you don't need to make an static members.
You can make your class like this
public class PayRoll {
//don't have to declare any member public since you have functions to return value
//don't need access specifier since they are private by default
String employeeId;
int hoursWorked;
double hourlyPay;
double TotalPayRoll=0; //you have to initialize it to zero
double Salary;
public PayRoll (String theEmployeeId, int theHoursWorked,
double theHourlyPay)
{
this.employeeId = theEmployeeId;
this.hoursWorked = theHoursWorked;
this.hourlyPay = theHourlyPay;
// Salary = hoursWorked*hourlyPay;
// TotalPayRoll = TotalPayRoll + Salary ;
//you do not need to do this since you have different functions for them
}
public double getTotalPayRoll()
{
return this.TotalPayRoll;
}
public String getTheEmployeeId()
{
return this.employeeId;
}
public int getTheHoursWorked()
{
return this.hoursWorked;
}
public double getTheHourlyPay()
{
return this.hourlyPay;
}
public double getSalary()
{
return this.Salary;
}
//don't need the increase method
public void changeTheHoursWorked (int amount)
{
hoursWorked += amount;
}
public void calculateSalary()
{
Salary = hoursWorked*hourlyPay;
}
public void calculateTotalPayRoll()
{
TotalPayRoll+=Salary;
}
//don't need the change hours function
}
Hope this helps :)

Unexpected type + non-static variable this cannot be referenced from a static context errors?

My code does not compile. How can I resolve the errors?
import java.util.*;
public class BankAccount{
private double balance;
public BankAccount(double b) {
balance = b;
}
public double getBalance(){
return balance;
}
public void deposit(double d){
balance += d;
}
public boolean withdraw(double d){
if(d > balance){
return false;
} else {
balance -= d;
return true;
}
}
public class SavingsAccount extends BankAccount{
private double interest;
public SavingsAccount(double k, double inRate){
super(k);
interest = inRate;
}
public void gainInterest(){
super.getBalance() = super.getBalance() * interest;
}
}
public static void main(String[] args) {
SavingsAccount test = new SavingsAccount(1000, .05);
test.gainInterest();
System.out.println(test.getBalance());
}
The following errors are
I get the unexpected type error at
super.getBalance() = super.getBalance() * interest; and the "non-static variable this cannot be referenced from a static context" at SavingsAccount test = new SavingsAccount(1000, .05);
You can't assign a value to a method.
You will need to assign the result to a variable or pass the result to another method, in this case you can use deposit, something like...
public void gainInterest(){
deposit(super.getBalance() * interest);
}

How can I record previous parameter values and add to new one?

I want to record old values of a parameter and add new parameter values upon the old ones, how can I do this in java?
For example how can I add up the "10" in the auto.fillUp and the "20" in the auto.fillUp?
public class Main {
public static void main(String[] args){
OdometerReading auto = new OdometerReading(15);
auto.fillUp(350, 10);
auto.fillUp(450, 20);
System.out.println("Miles per gallon: " + auto.calculateMPG());
}
}
OdometerReading Class:
public class OdometerReading {
public int myStartMiles;
public int myEndMiles;
public double myGallonsUsed;
public int milesInterval;
public double getMyGallonsUsedNew;
public OdometerReading(int assignedCarMiles){
myStartMiles = assignedCarMiles;
System.out.println("New car odometer reading: " + myStartMiles);
}
public void fillUp(int milesDriven, double gallonsUsed){
myEndMiles = milesDriven;
myGallonsUsed = gallonsUsed;
}
public double calculateMPG(){
milesInterval = myEndMiles - myStartMiles;
double mpg = milesInterval / myGallonsUsed;
return mpg;
}
public void reset(){
myStartMiles = myEndMiles;
myGallonsUsed = 0;
}
}
***Note: I am a beginner to Java & programming in general I'm sorry if this may be an "un-professional" question.
Just make the operation in the method, the state gets saved in the object variable and as long as you have a reference to the object you are good.
public void fillUp(int milesDriven, double gallonsUsed){
myEndMiles += milesDriven;
myGallonsUsed += gallonsUsed;
}
Note the + operator

Categories

Resources