I'm working on a project to simulate a car. The requirements are to demonstrate the operation of a car by filling it with fuel and then run the car until it has no more
fuel. Simulate the process of filling and running the car at different speeds. As the car is running, periodically print out the car’s current mileage, amount of fuel and speed.
I wrote some other classes to hold some methods that I will use to calculate the fuel, speed, and mileage. I'm just having a little trouble on how I should go about making it work like an actual car would, any help would be appreciated.
public class FuelGauge {
protected double fuel;
public FuelGauge()
{
fuel = 0.0;
}
public double getFuel()
{
return fuel;
}
public void setFuel(double fuel)
{
this.fuel = fuel;
}
public void fuelUp()
{
if(fuel<18)
fuel++;
}
public void fuelDown()
{
if(fuel>0)
fuel--;
}
}
public class Odometer extends FuelGauge {
private int mileage, mpg;
private int economy;
public int getMileage()
{
return mileage;
}
public void setMileage(int mileage)
{
this.mileage = mileage;
}
public int getMpg()
{
return mpg;
}
public void setMpg(int mpg)
{
this.mpg = mpg;
}
public void mileUp()
{
if(mileage<999999)
mileage++;
}
public void mileReset()
{
if(mileage>999999)
mileage = 0;
}
public void decreaseFuel(int fuel)
{
if(mileage == mpg)
fuelDown();
}
public int getEconomy()
{
return (int) (mileage/fuel);
}
public void setEconomy(int economy)
{
this.economy = economy;
}
}
public class Car extends Odometer{
private String name;
private int speed;
public Car()
{
name = "Car";
getMileage();
getMpg();
getEconomy();
getFuel();
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getSpeed()
{
return speed;
}
public void setSpeed(int speed)
{
this.speed = speed;
}
public void increaseSpeed()
{
if(speed<=120)
speed++;
}
public void decreaseSpeed()
{
if(speed>0)
speed--;
}
}
I would more recommend the contains vs isa relationship for the components of your car.
class FuelGauge { ... }
class Odometer { ...}
class Vehicle { ... }
class Car extends Vehicle
{
private FuelGauge fuelGauge = new FuelGauge();
private Odometer odometer = new Odometer();
...
}
Well, here are some suggestions:
Start the car.
Pull out from your driveway; if that's not needed, start driving
If you plan to drive at a fixed speed, you can calculate how long the ride would take in advantage, and just use a loop to update the distance and fuel; otherwise, you can store a set of speeds in an array, use a loop, and pass the variable speeds on each iteration (this might be a little hard to calculate how much fuel is left)
Hope that helps the inspiration running.
Here is the design of your car simulator application :
Identify Car class which will have odometer reading, current fuel inside tank etc as the instance variables.
Write a thread which continuously run with some sleep time of 100 millis or so for every iteration and inside the thread's run method you deal with the logic of incresing the odometer reading and decreasing the fuel in some proportion. make sure that your thread will run till the fuel in tank is greater than 0. if in case you can raise an event or alarm just in cse the fuel is below a certain constant.
Write the main class to initiate the class with full tank fuel (may be 40 ltrs a constant) and odometer reading to 0 and then start the thread.
Hope this is helpful.
-KishoreMadina
Related
I googled alot and the problem gives me a Headache because nobody can help me with it on Discord. Now I am here for help.
Thats the Class I use to make the Object
public class Main {
public static void main(String[] args) {
Konto mats = new Konto("Mats", 200);
mats.getAccount();
}
}
That is the class of it:
public class Konto extends Bankautomat{
String name;
int balance;
String prefix = "[Deutsche Bank]";
public Konto(String name, int balance){
this.name = name;
this.balance = balance;
System.out.println("New Account successfully registered!");
}
public void getAccount(){
System.out.printf("\n%s\nName: %s\nBalance: %d$\n", prefix, name, balance);
}
}
And now I want to make a Bankautomat class where I can deposit money on the Konto from "Mats"
public class Bankautomat {
public void deposit(int amount){
}
}
But I cant use mats.balance += amount
and the set or get things also dont help me
please help thank you <3
The way you have it set up, Konto extends Bankautomat right now. In other words, all Kontos are Bankautomats but the reverse is not the case. Since you only declare the field balance in the Konto class, this means it's a property of Kontos but not necessarily of all Bankautomats, so the Bankautomat object doesn't have this unless it's specifically a Konto.
To be able to access it in Bankautomat you should move the field to the Bankautomat class. Then, you'll be able to access it from both, since Konto is a Bankautomat and will inherit it. Something like this:
public class Konto extends Bankautomat{
String name;
String prefix = "[Deutsche Bank]";
public Konto(String name, int balance){
super(balance); // this calls the constructor of the superclass
this.name = name;
System.out.println("New Account successfully registered!");
}
public void getAccount(){
System.out.printf("\n%s\nName: %s\nBalance: %d$\n", this.prefix, this.name, this.balance);
}
}
and the other class:
public class Bankautomat {
int balance;
public Bankautomat(int balance) {
this.balance = balance;
}
public void deposit(int amount){
...
}
}
I have two classes, Main.java and Car.java
Main.java:
class Main
{
public static void main(String[] args)
{
Car ferrari = new Car(18, 25.43);
System.out.println(ferrari.efficiency);
}
}
Car.java:
class Car
{
public Car(double mpg, double initFuel)
{
double efficiency = mpg;
double fuel = initFuel;
}
}
I obviously tried to assign efficiency to the first constructor passed in when creating the object, but that doesn't seem to work (i.e. the variable is not found when I use the println in Main.java). How do I assign variables to objects to be referenced later?
You're using local variables in your Car's constructor. Their lifecycle bounded within your constructor. Just declare your members in your class and use getters and setters to access them.
class Car
{
private double efficiency;
private double fuel;
public Car(double mpg, double initFuel)
{
this.efficiency = mpg;
this.fuel = initFuel;
}
public void setEfficiency(double efficiency) {
this.efficiency = efficiency;
}
public double getEfficiency() {
return efficiency;
}
// Same thing for fuel...
}
And in your Main:
class Main
{
public static void main(String[] args)
{
Car ferrari = new Car(18, 25.43);
System.out.println(ferrari.getEfficiency());
}
}
Make efficiency and fuel global to your class rather than local to your constructor.
Main.java
public class Main
{
public static void main(String[] args)
{
Car ferrari = new Car(18, 25.43);
System.out.println(ferrari.efficiency);
}
}
Car.java
public class Car
{
public double efficiency;
public double fuel;
public Car(double mpg, double initFuel)
{
efficiency = mpg;
fuel = initFuel;
}
}
That should work. But you can make the instance variables private instead of public and use setters/getters
Also set your Main and Car to public so they can be accessible/instantiated from another class.
Main.java
public class Main
{
public static void main(String[] args)
{
Car ferrari = new Car(18, 25.43);
System.out.println(ferrari.getEfficiency());
}
}
Car.java
public class Car
{
private double efficiency;
private double fuel;
public Car(double mpg, double initFuel)
{
efficiency = mpg;
fuel = initFuel;
}
public double getEfficiency(){
return efficiency;
}
}
Change your Car class to:
class Car
{
private double efficiency;
private double fuel;
public Car(double mpg, double initFuel)
{
this.efficiency = mpg;
this.fuel = initFuel;
}
}
You need to declare the variables on the Class scope instead of the local scope when using a variable for an instantiated Object. These variables typically are set from the Constructor so they can be accessed later from the Object itself.
Most of the time these are also declared as private with a separate method to get and set them instead of directly accessing them.
Example:
public double getEfficiency(){
return this.efficiency;
}
public void setEfficiency(double mpg){
this.efficiency = mpg;
}
Most IDE's can auto generate Getters and Setters for you so you do not need to hand write them for every variable.
To use the getter/setter you call the method from an instance of the class rather than using the variable directly:
Car tesla = new Car(35.5, 90.5);
tesla.efficiency = 15.5; //YOU CAN'T DO THIS
tesla.setEfficiency(15.5); //Do this instead
System.out.println(tesla.getEfficiency()); //Will print 15.5
I need to create a "super" enum (here ESideItem) which will keep record of "sub" enums (SALAD, FRY, TACO) & I need to access "sub" enum's fields(price) from outside too.
I meant "super" as main type & "sub" as sub-type of that main type.
There can be many types of SideItems (FRY, SALAD, TACO) for a meal & each of these sideitems can be of many types (i.e SALAD can be CHICKEN or AFGHAN or MIMOSA etc).
Following Ray Tayek's answer to this question I've implemented this:
public abstract class SideItem {
public enum FRY {
FRENCHFRY(25.25f), SEASONEDCURLYFRY(30.10f);
private float price;
FRY(float price) {
this.price = price;
}
public float getPrice() {
return price;
}
}
public enum SALAD{
AFGHANSALAD(50.25f), CHICKENSALAD(40.10f), MIMOSASALAD(45.89f);
private float price;
SALAD(float price) {
this.price = price;
}
public float getPrice() {
return price;
}
}
public enum TACO{
MONSTERTACO(26.25f), NACHOMONSTERTACO(35.10f);
private float price;
TACO(float price) {
this.price = price;
}
public float getPrice() {
return price;
}
}
public enum ESideItem {
FRY(SideItem.FRY.FRENCHFRY), SALAD(SideItem.SALAD.AFGHANSALAD), TACO(SideItem.TACO.MONSTERTACO);
ESideItem(Enum e) {
this.e = e;
}
public Object[] subValues() {
return e.getDeclaringClass().getEnumConstants();
}
final Enum e;
}
}
I implementd Main.java as follows:
public class Main {
public static void main(String[] args) {
for(SideItem.ESideItem aSideItem : SideItem.ESideItem.values()){
System.out.println(aSideItem);
for(Object o : aSideItem.subValues()){
System.out.format("%-15s",o);
System.out.println();
}
System.out.println();
}
}
}
The output is:
FRY
FRENCHFRY
SEASONEDCURLYFRY
SALAD
AFGHANSALAD
CHICKENSALAD
MIMOSASALAD
TACO
MONSTERTACO
NACHOMONSTERTACO
Main.java is like client side & SideItem.java is like server side. I can change or add any instance in the ESubItem enum from SideItem.java. Main.java should give output according to that change
But I do need to get price of these individual TACO's, SALAD's, FRY's . Is there any way to access these fields from Main.java using enum?
If not then what kind of data structure should I use to solve this problem ?
You should be using an interface:
interface Food
{
float getPrice();
}
public enum Fry implements Food
{
FRENCH_FRY(25.25f), SEASONED_CURLY_FRY(30.10f);
private final float price;
FRY(float price) {
this.price = price;
}
#Override
public float getPrice() {
return price;
}
}
And the same for the other two...
Then you can compose them like so:
public enum Meal implements Food {
HAPPY_MEAL(Fry.FRENCH_FRY, Fry.SEASONED_CURLY_FRY),
SAD_MEAL(Salad.AFGHAN_SALAD);
private final List<Food> items;
Meal (Food... items) {
this.items = Arrays.asList(food);
}
#Override
public float getPrice()
{
return (float) items.stream().mapToDouble(Food::getPrice).sum();
}
}
If you want to access the price for calculations etc. the easiest way is to make all those enums implement an interface with public float getPrice().
For display purposes you would only need to modify the toString() of each enum.
The enum ESideItem and SideItem classes seem unnecessary though. Especially the ESideItem doesn't seem like it should be an enum at all, and the way you're using getDeclaringClass().getEnumConstants() is just a really bad idea.
You will need to something like:
for(Object o : aSideItem.subValues()){
if(o instanceof SideItem.FRY)
((SideItem.FRY)o).getPrice()
You can define an interface, say
public interface Priced {
double getPrice();
}
The enums can implement that
public enum FRY implements Priced { // no further change needed, method already there
and you can return an array of Priced with your subValues().
public Priced[] subValues() {
return Stream.of(FRY.values(), SALAD.values(), TACO.values()).
toArray(Priced[]::new);
}
I'm not entirely sure if the latter works this way, but being able to implement an interface in your enum is the main point.
I have to model breakwater that controls permissions in certain coast. My solution implements a class "Ship" and classes "OilShip", "FishingShip" and "CarriageShip", I used inheritance and made
public class OilShip extends Ship{
...
}
public class FishingShip extends Ship{
...
}
public class CarriageShip extends Ship{
...
}
In another class I have Ship ship=new Ship(...); and I'd like to somehow make an Oilship into Ship, i.e.
public Class Abcd{
Ship ship;
public Abcd(OilShip oship){
ship=oship; //*************
}
}
There seems to be a problem with the code, please tell me.
Make sure you call the superclass' constructor inside your subclasses' constructors.
This solution works fine for me:
public class Ship {
private String name;
private int weight;
public Ship(String name, int weight) {
this.name = name;
this.weight = weight;
}
}
class OilShip extends Ship {
private int oilCapacity;
public OilShip(int oilCapacity, String name, int weight) {
super(name, weight);
this.oilCapacity = oilCapacity;
}
}
class FishingShip extends Ship {
private int fisherMen;
public FishingShip(int fisherMen, String name, int weight) {
super(name, weight);
this.fisherMen = fisherMen;
}
}
class CarriageShip extends Ship {
private int containers;
public CarriageShip(int containers, String name, int weight) {
super(name, weight);
this.containers = containers;
}
}
As mentioned before, Java-classes should always be given a name, where the first character is in UPPERCASE and the same with each new word --> CamelCase
You don't need different constructors. The awesome thing behind using inheritance here, is, that no matter what subclass from the superclass "Ship" you put into your constructor in "abcd", it will be accepted:
public class Abcd {
private Ship ship;
public Abcd(Ship ship){
this.ship = ship;
}
}
I want to be able to give a specific value to discount depending on certain requirements like the following age: > 25 and profession = teacher / professor get 10% discount, age < 25 and gradepoint > 7 get 25% discount
this is my code so far I am using double OO paradigm:
public class customer {
//attribute definitions
private String name;
private String address;
private String profession;
private Integer age;
private Integer gradepoint;
private double discount;
//constructor
public customer(String newName, String newAddress, String newProfession, Integer newAge, Integer newGradepoint, double newDiscount)
{
setName(newName);
setAddress(newAddress);
setProfession(newProfession);
setAge(newAge);
setGradepoint(newGradepoint);
setDiscount (newDiscount);
}
//getters
public String getName()
{ return name;}
public String getAddress()
{ return address;}
public String getProfession()
{ return profession;}
public Integer getAge()
{ return age;}
public Integer getGradepoint()
{ return gradepoint;}
public double getDiscount()
{ return discount;}
//setters
public void setName (String newName)
{ name = newName;}
public void setAddress (String newAddress)
{ address = newAddress;}
public void setProfession (String newProfession)
{ profession = newProfession;}
public void setAge (Integer newAge)
{ age = newAge;}
public void setGradepoint (Integer newGradepoint)
{ gradepoint = newGradepoint;}
public void setDiscount (double newDiscount)
{ discount = newDiscount;}
//methods
}
Would I need to create a sub class called discount or each type of discount? or I can write a method directly into this customer class to control the discount?
write a method directly into this customer class to control the discount?
This. Make it a calculated field. Kill setDiscount function, kill discount variable, and make the getDiscount function into something like:
public double getDiscount() {
if (...) return ...;
if (....) return ...;
...
}
...unless you want to have this as the default discount, and still allow modification, in which case keep discount as a property, and move this whole logic into the constructor, having conditional setDiscount() calls.
Your getDiscount function would ideally do the calculation and return the appropriate discount for the current object. For example:
public double getDiscount()
{
if (getAge() < 25 && getGradepoint() > 7)
{
return .25;
}
else if // other logic...
}
Although not the simplest solution, I would abstract the discount calculation to a separate interface and class as well as having an override discount value in the customer object.
E.g.
public interface DiscountManager<T>
{
public double getDiscount(T discountObject);
}
public abstract class AbstractCustomerDiscountManager extends DiscountManager<Customer>
{
public double getDiscount(Customer customer)
{
if (customer.hasCustomDiscount()) { return customer.getDiscount(); }
else { return calculateDiscount(customer); }
}
public abstract double calculateDiscount(Customer customer);
}
public class DefaultDiscountManager extends AbstractCustomerDiscountManager
{
public double calculateDiscount(Customer customer)
{
double discount = 0;
if ((customer.getAge() != null) && (customer.getAge() < 25)) { discount += 25; }
...
return discount;
}
}
Probably over time different rules evolve. At the spot where the discounting takes place, in the order, the discount and and a reference to the rule applied should be stored together.
This kind of business logic could have its own class. A generic solution would even be to store the rule as scriptable code (BeanShell = Java, or JavaScript) and use java's scripting API. So that this kind of business logic resides more with the business managers, and the rules can be presented and edited.