Need explanation of java Class collaboration/aggregation - java

I'm working on an assignment where I need to make 3 classes for a car simulator. One for the fuel and one for the mileage. "The mileage class should be able to work with a FuelGauge object. It should decrease the FuelGauge object's current amount of fuel by 1 gallon for every 24 miles traveled. (The car's fuel economy is 24 miles per gallon)." I'm just really struggling on understanding how to properly link the classes together so that they can do what is necessary.
A good explanation from someone would be greatly appreciated.

I hope I understand your problem correctly.
Simple answer is that FuelGauge class will have attribute amount, which will be accessible through simple setter/getter.
public class FuelGague {
private double amount;
// Starting amount of fuel
public FuelGague(double amount) {
this.amount = amount;
}
// Not sure if you really need this method for your solution. This is classic setter method.
public void setAmount(double amount) {
this.amount = amount;
}
public double getAmount() {
return amount;
}
// I guess this is what do you actually want to do
public void changeAmount(double difference) {
amount += difference;
}
}
public class Mileage {
private FuelGague fuelGague;
public Mileage(FuelGague fuelGague) {
this.fuelGague = fuelGague;
}
// This will be main method where you can decrease amount for guelGague
public void methodForMileage() {
fuelGague.changeAmount(-1);
}
public FuelGague getFuelGague() {
return fuelGague;
}
public void setFuelGague(FuelGague fuelGague) {
this.fuelGague = fuelGague;
}
public static void main(String[] args)
{
FuelGague fuelGague= new FuelGague(50);
Mileage mil = new Mileage(fuelGague);
}
}
As you can see Mileage class has refference to fuelGague object which is passed in constructor and it can be manipulated by public method of FuelGague class. I added set method for Mileage class so you can even set different FuelGague class object.

Related

Why is my method undefined for this type?

I'm not sure why Eclipse is giving me this error, I cannot run the exchange method for any of my desired classes:
The method exchange(Currency, double) is undefined for the type Currency
Some of the code methods listed have not been fully implemented due to my issues compiling to begin with.
What simple mistake am I making?
public abstract class Currency {
String currencyName;
double totalFunds;
//Exchange money between planets
public abstract double toEarthDollars(double amount);
public abstract double fromEarthDollars(double EarthDollars);
public static void main(String[] args) {
//TEST INPUT CODE
Currency mars = new Mars(100.00);
Currency neptune = new Neptune(100.00);
Currency saturn = new Saturn(100.00);
System.out.println("----- Exchanges -----");
mars.exchange(saturn,25.0);
neptune.exchange(saturn, 10.0);
saturn.exchange(mars, 122.0);
saturn.exchange(mars, 121.0);
}
}
public interface Exchangeable {
//rates should be encapsulated and accessed from here
double EarthDollar = 1;
double MarsMoney = 1.3;
double SaturnSilver = 0.87;
double NeptuneNuggets = 2;
public void exchange(Exchangeable other, double amount);
}
public class Mars extends Currency implements Exchangeable {
public Mars(double amount) {
currencyName = "MarsMoney";
totalFunds = amount;
}
public double toEarthDollars(double amount) {
return amount * (Exchangeable.EarthDollar/Exchangeable.MarsMoney);
}
public double fromEarthDollars(double EarthDollars) {
return EarthDollars * (Exchangeable.MarsMoney/Exchangeable.EarthDollar);
}
public void exchange(Exchangeable other, double amount) {
System.out.println("Hello");
//double transfer = this.toEarthDollars(amount);
//transfer = ((Mars) other).fromEarthDollars(transfer);
}
}
Your abstract Currency class does not implement the Exchangeable interface. Change
public abstract class Currency {
to
public abstract class Currency implements Exchangeable {
I think your Currency class does not know a method of exchange only Exchangeable has that.
So you might want to cast:
Currency mars = new Mars(100.00);
Exchangeable marsEx = (Exchangeable)mars;
Exchangeable saturnEx = (Exchangeable)saturn;
marsEx.exchange(saturnEx,25.0);
You also might want to check if that Currency can be casted to Exchangeable as maybe not all currencies are exchangeable.
Also you might need to cast saturn, as Currency can not be passed to the exchange method.

How do i perform a calculation within a setter method in java?

I have two classes within a java project, one is the Employee1 class and the other is the info class. Within the Employee 1 class I have this code:
public class Employee1 {
String employeeName;
int hoursWorked;
double rateOfPay;
double wages;
public Employee1(String name, int hours, double pay) {
employeeName=name;
hoursWorked=hours;
rateOfPay=pay;
}
public String getName() {
return employeeName;
}
public void setName(String xName) {
employeeName = xName;
}
public double getHours() {
return hoursWorked;
}
public void setHours(int xHours) {
hoursWorked = xHours;
}
public double getPay() {
return rateOfPay;
}
public void setPay(double xPay) {
rateOfPay = xPay;
}
public double calculateWages () {
wages= hoursWorked * rateOfPay;
return wages;
}
public void print() {
System.out.println("name:"+ employeeName);
System.out.println("hours " + hoursWorked);
System.out.println("Wages Earned"+ wages);
}
}
Within my info class I have this code:
public class Info {
public static void main(String[] args) {
Employee1 x= new Employee1("Sarah",40,7.25);
Employee1 y=new Employee1("Bob",30,8.00);
Employee1 z= new Employee1("Todd",26, 8.25);
x.print();
}
}
My problem right now is that I am attempting to create a calculation for wages within my Employee1 class as you can see with my calculateWages method. However, whenever I call my print method for my existing employee x the wages always come out to be 0.0 and I am unsure why this is happening. I have preexisting variables for each of my Employee1 objects and I am still getting a 0.0 value for all of their wages but the rest of their information is printed correctly. Can anyone help me with this issue? Thank you!
In the code you provide there is not a setter method, instead there is a getter one. And yes, you can made calculation in both, getter and setter.
public void setAmount(int amount){
this.amount = quantity * price;
}
public void getAmount(){
return this.amount + otherProperty;
}
Lets start with this:
I'm new to programming but I know that this type of method is known as a setter.
No it isn't.
In OO, the code (mostly) consists of classes which consist of state (fields) and methods that (typically) operate on that state.
By convention ...
A setter is a method that sets a field to a new value provided as a method argument.
A getter is a method that returns the value of a field.
Your method is neither a setter or a (pure) getter:
It is not a setter because it doesn't set wages to a supplied value. (It is doing the calculation based on previously supplied values.)
You could view it as a getter for the wages field, but it is "impure" in that it updates the field as well as returning its value.
Every time I go to print out the "wages" variable it just gives me a zero and nothing else, I have the other variables hoursWorked & rateOfPay defined in the main
We cannot explain this without seeing the rest of your code. However, I suspect that the problem is one of the following:
Either of hoursWorked or rateOfPay is zero ... because they are not being correctly set / initialized to non-zero values.
The calculateWages method is not being called.
You have multiple instances of the class that defined this method ... and your code is looking at the wrong one.
Possibly ... some of the variables involved have been incorrectly declared as static.s
UPDATE - Now that I see your code, the reason that wages is zero is that your code doesn't call calculateWages.
You can pass those values to the calculateWages () method.
Try this
public double calculateWages (int hoursWorked, double rateOfPay) {
return hoursWorked * rateOfPay;
}
In the best practice of OOP your method should have two arguments:
e.g.
public class Answer1 {
public static double calculateWages (int hoursWorked, double rateOfPay){
return hoursWorked * rateOfPay;
}
public static void main(String[] args) {
System.out.println(calculateWages(6, 5.24));
}
}
You may want to simplify this by creating a class, outside of the main class with the main method, that does this ONE specific job of calculating a wage. We call this "isolation" in programming, and we want to isolate one class from another and make sure each class only does one particular job. Here is an example of a class that will get the total wage:
public class WagesCalc {
public static double calculateWages(int hoursWorked, double hourlyWage) {
double wage = (double)hoursWorked * hourlyWage;
return wage;
}
}
In the code above we can create a class that calculates the wages called WagesCalc. Within it, we can create a method called calculate wages. You can add hours worked, and the hourly wage as the arguments for the class. We then add a variable, and then return an the wage. We make this method static so that we can return it without an instance of the class being created. Here is the code in the main method:
public class App {
public static void main( String[] args )throws IOException{
double wages = WagesCalc.calculateWages(23, 23.50);
System.out.println("My total wage is $" + wages);
}
}
And here is the output:
My total wage is $540.5

Using Observable/Observer with two different double variables?

I have a class that monitors the stock market. It holds 2 values (doubles) the daily high and the daily low. I want to monitor these variables from another class and take action if either changes. (i.e. change a limit order)
So, I have a class LiveOrderBook extends Observable and two methods inside that update the price:
public void setDailyLow(double price){
low = price;
setChanged();
notifyObservers(low);
}
public void setDailyHigh(double price){
high = price;
setChanged();
notifyObservers(high);
}
I need to observe these price variables so I made a class PriceObserver implements Observer. My plan is to create PriceObserver objects inside my Bid class that changes stock market bids.
My PriceObserver class
private double low;
private double high;
public PriceObserver(){
low = 0;
high = 0;
}
public void update(Observable arg0, Object arg1) {
// TODO Auto-generated method stub
}
How do I now specify which double should be updated? I can't check if arg0 == the variable name from the other class, so how is this done?
An easy (and useful) approach is to first create different event classes that can get dispatched:
public class LowPriceChangedEvent {
private double price;
// Constructor and getter up to you.
}
public class HighPriceChangedEvent {
private double price;
// Constructor and getter up to you.
}
Now you can dispatch these events in your LiveOrderBook class:
public void setDailyLow(double price){
low = price;
setChanged();
notifyObservers(new LowPriceChangedEvent(low));
}
public void setDailyHigh(double price){
high = price;
setChanged();
notifyObservers(new HighPriceChangedEvent(low));
}
Your PriceObserver now easily can distinguish the events by doing a simple instanceOf check:
public class PriceObserver implements Observer {
#Override
public void update(Observable o, Object arg) {
if (arg instanceOf LowPriceChangedEvent) {
...
} else if (arg instanceOf HighPriceChangedEvent) {
...
} else {
...
}
}
}
Your arg1 is an Object. I would suggest calling your notifyObservers method with a double[] (all arrays are castable to Object).
i.e.
notifyObservers(new double[] {low, high});

Java bank account project issue

So, I followed the online youtube tutorial for this, and it worked for the tutorial instructor, but not me... However, only because it wants a "getBalance" class in the source classes. If someone could help me with this, it would be greatly appreciated. I'm new to Java, and I do have some reading to catch up on in the book... So here's the program and its class setup:
BankAccountDemo.java
package bankaccountdemo;
import java.text.DecimalFormat;
public class BankAccountDemo {
public static void main(String[] args) {
BankAccount account1 = new BankAccount(12.00);
BankAccount account2 = new BankAccount(account1);
DecimalFormat dollar = new DecimalFormat("#.##0.00");
System.out.print("The balance in account #1 is $" + dollar.format(account1.getBalance()));
System.out.print("The balance in account #2 is $" + dollar.format(account2.getBalance()));
}
}
BankAccount.java
package bankaccountdemo;
public class BankAccount {
private double balance;
public BankAccount() {
balance = 0.0;
}
public BankAccount(BankAccount obj) {
balance = obj.balance;
}
public BankAccount(double startBalance) {
balance = startBalance;
}
}
I am aware that this is a pretty simple fix, but as I said.. I have some reading to catch up on. I understood the lottery problem better than this very simple bug.
it wants a "getBalance" class in the source classes.
It doesn't want a class it wants a method that is called on your bankaccount object.
account1.getBalance()
So you need to create a method in your BankAccount class.
public double getBalance(){
return balance;
}
This function is called a getter function. In OOP languages an object's properties are usually created as private and can be modified/set and read/get using this setter and getter functions.
so you can create another function like
public void setBalance(double balance){
this.balance = balance;
}
and then you can use
account1.setBalance(10.0);
to set the amount to 10.0
As you said, you need a getBalance() method in BankAccount:
public double getBalance() {
return balance;
}

Applying two different sets of interest rates to two objects of the same class

How can I make two objects of the same class use different interest rates?
I need to make it so that savingAccount2 and savingAccount3 use different interest rates.
savingAccount1UI savingAccount2 = new savingAccount1UI();
savingAccount1UI savingAccount3 = new savingAccount1UI();
These objects both inherit from a class called Account.java. This superclass contains all the methods that include how to calculate the interest.
Here is the current method in the superclass that calculates the 1 year interest account.java:
//add interest
public void interest(double interest){
if(balance<target){
interest = balance*lowRate;
balance = balance + interest;
updatebalance();
} else{
interest=balance*highRate;
balance = balance + interest;
}
updatebalance();
}
Here is the button that triggers this method:
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
interest(Float.parseFloat(balanceLabel.getText().substring(1)));
Currently I am using variables with double values assigned to them, but of course this means that both objects(savingAccount2 and savingAccount3) use the same numbers. Note that these variables are stored in the Account.java superclass Like so:
public double lowRate = 0.019;
public double highRate = 0.025;
I think I may need to use a constructor for each object, with pre-set values to solve my issue but I don't understand how to implement that idea. Any suggestions?
You can write method in class Account to set the values of lowRate and highRate like:
public void setRates(double lr, double hr){
lowRate=lr;
highRate=hr;
}
Now when you create an object of class SavingsAccount, you can do:
SavingsAccount sa=new SavingsAccount();
sa.setRates(0.019,0.025);
Just do it:
savingAccount1UI savingAccount2 = new savingAccount1UI(0.019,0.025);
in class definition:
savingAccount1UI(float lowRate,float highRate) {
this.lowRate = lowRate;
this.highRate = highRate;
}
when computing pass also the class to the method and access the inners value.
public void interest(double interest,savingAccount1UI account){
if(balance<target){
interest = balance*account.lowRate;
balance = balance + interest;
updatebalance();
} else{
interest=balance*account.highRate;
balance = balance + interest;
}
updatebalance();
}
It seems you are looking for this:
public class Account {
private double lowRate;
private double highRate;
//other fields
public Acount(double lowRate, double highRate) {
this.lowRate = lowRate;
this.highRate = highRate;
}
// your interest() method
// getters & setters
}
public class SavingAccount1UI extends Account {
public SavingAccount1UI(double lowRate, double highRate) {
super(lowRate, highRate);
}
// rest of your stuff
}
This way you are only able to create an object passing the values you need, like:
SavingAccount1UI savingAccount = new SavingAccount1UI(0.019, 0.025);
Now every time you call your interest() method, it will take into consideration the values passed.

Categories