Fuel consumption class java [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
import java.util.Scanner;
public class LKM {
public static void main(String[] args){
Scanner keyboard=new Scanner(System.in);
String startKm=keyboard.nextLine();
String endKm=keyboard.nextLine();
String liters=keyboard.nextLine();
}
public void Car (double startOdo, double endOdo, double liters){
startKm=startOdo;
endKm=endOdo;
liters=liters;
}
public static void LKM(String args[]){
calculateLKM red=new Car(1,20,10);
Car white=new Car(5,10,5);
System.out.println((red.endKm-red.startKm)/red.liters);
System.out.println((white.endKm-white.startKm)/white.liters);
}
}
I have to define a class that calculates fuel consumption of a car using one constructors and one method. I tried learning class and objects but it didn't work so well..I need just a few tips. Thank you.

I think you are confusing Method and Constructor.
When you do "New Car()", you try to invoke Car Construstor.
So to do it, you need a class "Car" with a Constructor inside.
Create a new file named "Car.java" and insert this code inside :
public class Car {
public Car(double startOdo, double endOdo, double liters){
this.startOdo = startOdo;
this.endOdo = endOdo;
this.liters = liters;
}
}
But if you wan't to do :
startKm=startOdo;
endKm=endOdo;
liters=liters;
You need fields inside your Car Class. So add startKm, endOdo, liters as fields in your Car class :
private double startOdo;
private double endOdo;
private double liters;
Then add some getters and setters to access your fields :
public double getStartOdo() {
return startOdo;
}
public void setStartOdo(double startOdo) {
this.startOdo = startOdo;
}
public double getEndOdo() {
return endOdo;
}
public void setEndOdo(double endOdo) {
this.endOdo = endOdo;
}
public double getLiters() {
return liters;
}
public void setLiters(double liters) {
this.liters = liters;
}
This would give you something like this :
public class Car {
private double startOdo;
private double endOdo;
private double liters;
public double getStartOdo() {
return startOdo;
}
public void setStartOdo(double startOdo) {
this.startOdo = startOdo;
}
public double getEndOdo() {
return endOdo;
}
public void setEndOdo(double endOdo) {
this.endOdo = endOdo;
}
public double getLiters() {
return liters;
}
public void setLiters(double liters) {
this.liters = liters;
}
public Car(double startOdo, double endOdo, double liters){
this.startOdo=startOdo;
this.endOdo=endOdo;
this.liters=liters;
}
}
Finally, you will be able to do what you want in your main file. You just have to call "getStartOdo()", "getEndOdo()" and "getLiters()" to retrieve your datas and display it with System.out.println() method.
Oh, and don't forget to call your "LKM" method in your Main method, otherwise nothing will happen.

Related

What's the best RPG coding practice according to OOP design? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I'm working on a RPG game and there's a Player and an Equipment class. Should I implement mountEquipment() method in Player class, which it will be something like
public class Player {
private ArrayList<Equipment> equipments;
public void mountEquipment(Equipment e){
// how can i know what attributes
// Equipment will change in Player?
equipments.add(e);
}
}
or should I implement in Equipment class, which will be
public class Equipment {
public void mountEquipment(Player p){
// here i can access all Player attributes
p.addStrength(50);
p.addHP(100);
p.addEquipment(this);
}
}
It's easier to acess Player attributes defining mountEquipment in Equipment class, but I think it makes more sense having mountEquipment in Player class, even thought it will be harder to changing Player attributes. For example, a Sword can change strength and MagicWand can change strenght and luck, for example.
Where should I implement this class in this case?
In the simple case, a player's stats are basically just an aggregation of their base stats + their equipment stats.
Seems like an opportunity to share an interface:
public interface StatProvider {
int health();
int intellect();
}
public class Ring implements StatProvider {
#Override
public int health() {
return 0;
}
#Override
public int intellect() {
return 5;
}
}
public class Mage implements StatProvider {
private final int baseHealth = 100;
private final int baseIntellect = 20;
private List<StatProvider> equipment;
#Override
public int health() {
return baseHealth + equipment.stream().mapToInt(StatProvider::health).sum();
}
#Override
public int intellect() {
return baseIntellect + equipment.stream().mapToInt(StatProvider::intellect).sum();
}
}
Works well with the decorator pattern too maybe
public class HealthDoublingEnchantment implements StatProvider {
private final StatProvider delegate;
public HealthDoublingEnchantment(StatProvider delegate) {
this.delegate = delegate;
}
#Override
public int health() {
return delegate.health() * 2;
}
#Override
public int intellect() {
return delegate.intellect();
}
}
e.g.
new HealthDoublingEnchantment(new Ring());

Is this a valid code for achieving abstraction in java using abstract classes and abstract methods [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Is this a correct method to achieve abstraction? As this in the abstract class
public abstract class Employee {
private String name, address;
int basicSalary;
public String getName(){
return name;
}
public String getAddress(){
return address;
}
public int getbasicSalary(){
return basicSalary;
}
public void setName(String name){
this.name= name;
}
public void setAddress(String address){
this.address= address;
}
public void setBasicSalary(int basicSalary){
this.basicSalary= basicSalary;
}
public abstract int getMonthlySalary();
}
This class extends the abstract employee class
class NormalEmployee extends Employee {
public NormalEmployee() {
// TODO Auto-generated constructor stub
}
public void setBasicSalary(int basicSalary) {
this.basicSalary=basicSalary;
};
// Method override for salarycalculation
#Override
public int getMonthlySalary() {
// TODO Auto-generated method stub
int monthlySalaryOfNormalEmployee= 1200;
System.out.println("Normal Employee Salary: "+monthlySalaryOfNormalEmployee);
return monthlySalaryOfNormalEmployee;
}
}
public class BonusEmployee extends NormalEmployee {
int bonusAmount;
This class extends normal employee class which is already inherits methods from employee class
public BonusEmployee() {
// TODO Auto-generated constructor stub
}
public int getBonus(){
return bonusAmount;
}
public static void main(String[] args) {
// Creating objects and calling methods
BonusEmployee bE= new BonusEmployee();
NormalEmployee nE= new NormalEmployee();
bE.setBonus(1200);
bE.setBasicSalary(1500);
bE.getMonthlySalary();
nE.getMonthlySalary();
}
public void setBonus(int bonusAmount){
this.bonusAmount=bonusAmount;
}
#Override
public int getMonthlySalary() {
int getMonthlySalary= basicSalary + getBonus();
System.out.println("Bonus Employee Salary: "+getMonthlySalary);
return basicSalary;
}
}
Since its giving me expected results so don't know if the implementation is right or not!
Abstraction in any programming language is more of a concept or approach for modeling aspects of the real world as software. Abstraction is taking something which is complex in nature and representing it in software in a way that is easy to understand or use, but still models or retains the essential elements of the concept in the real world.
To write some code and then ask 'have I achieved abstraction' would depend on what it is that you are attempting to represent in code.
There's a good definition of abstraction in software development in this article here: https://en.wikipedia.org/wiki/Abstraction#In_computer_science

Having problems with constructor

I'm new to java and trying to create a simple code checking the gas usage of a given car with given miles per gallon and gas but every time I try to initialize the variables, it keeps giving me errors. inTank and mpg say that only final is permitted and the constructors can't initialize the variable parameters for some reason. If someone could explain to me why and how to fix this I would be grateful. Happens in the Udacity IDE and Ecclipse.
public class MileagePrinter {
public static void main(String[] args)
{
// your code here
private double inTank;
private double mpg;
public MileagePrinter(double gasInTank, double milesPerGallon) {
inTank = gasInTank;
mpg = milesPerGallon;
}
}
}
Reorder the code... you have class variables and a constructor inside the main method...
it must look like
public class MileagePrinter {
private double inTank;
private double mpg;
public MileagePrinter(double gasInTank, double milesPerGallon) {
inTank = gasInTank;
mpg = milesPerGallon;
}
public static void main(String[] args){
// your code here
}
}
Main method and constructor are different from each other. Main is the starting point of execution of a program whereas constructor is used to create an object. We need to take constructor out of main method here, e.g.
public class MileagePrinter {
private double inTank;
private double mpg;
public MileagePrinter(double gasInTank, double milesPerGallon) {
inTank = gasInTank;
mpg = milesPerGallon;
}
public static void main(String[] args){
MileagePrinter pointer = new MileagePrinter(10d, 100d); //create object using constructor
}
}
Personally I prefer to separate the main in a class Main (for example, the name isn't important) for an organization of this type:
main.java :
public class Main {
public static void main(String[] args) {
// your code here
}
}
MileagePrinter.java :
public class MileagePrinter {
private double inTank;
private double mpg;
public MileagePrinter(double gasInTank, double milesPerGallon) {
inTank = gasInTank;
mpg = milesPerGallon;
}
}

How To implement abstract function which uses data members of parent class [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have the following abstract class :
abstract class OutDoorGames
{
protected String name;
protected int num_players;
protected int min_of_play;
abstract void game (String a,int g,int r);
};
I want the public void game function to assign values to the data members to the objects.
This Is The Class Which Implements The abstract void game (String a,int g,int r) :
class Cricket extends OuterDoorGames
{
public void game (String name,int num_players,int min_of_play)
{
OutDoorGames::name = name ;
OutDoorGames::num_players = num_players ;
OutDoorGames::min_of_play = min_of_play ;
}
}
But its giving Error When Compiled..
I also tried this :
class Cricket extends OuterDoorGames
{
public void game (String name,int num_players,int min_of_play)
{
this.name = name ;
this.num_players = num_players ;
this.min_of_play = min_of_play ;
}
}
This is also not working...
I am new to Java...How Should I Implement This Function.....??
First of all you got the names wrong.. Notice the name you gave to the parent abstract class OutDoorGames is not the same as you wrote when extended it OuterDoorGames.
As a practice, you can also try making a constructor in the parent abstract class which sets the 3 members and then just call it from within the constructor of the child class
An example of such usage:
public abstract class Bicycle {
// the Bicycle class has three fields
public int cadence;
public int gear;
public int speed;
// the Bicycle class has one constructor
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
// the Bicycle class has four methods
public void setCadence(int newValue) {
cadence = newValue;
}
public void setGear(int newValue) {
gear = newValue;
}
public void applyBrake(int decrement) {
speed -= decrement;
}
public void speedUp(int increment) {
speed += increment;
} }
public class MountainBike extends Bicycle {
// the MountainBike subclass adds one field
public int seatHeight;
// the MountainBike subclass has one constructor
public MountainBike(int startHeight,
int startCadence,
int startSpeed,
int startGear) {
super(startCadence, startSpeed, startGear);
seatHeight = startHeight;
}
// the MountainBike subclass adds one method
public void setHeight(int newValue) {
seatHeight = newValue;
}
}
Notice the super call which activates the parent class constructor. Just change it to accept your 3 arguments in the parent class
class Cricket extends OuterDoorGames
If you are getting a OuterDoorGames cannot be resolved to a type, then it's a typo. Your abstract class is named as "OutDoorGames". Once you correct that, your Cricket class should just work fine.
The only error I can see with the second one is that the class name is wrong. The first class you defined (your abstract class) is called "OutDoorGames", but you're trying to extend "OuterDoorGames".

Private access errors

I'm having trouble with a problem I'm working on for class.
The errors occurring are
TC1.java:17: error: myQuantity has private access in CheckItem
items[i].myQuantity=quantities[i];
and
TC1.java:20: error: myPrice has private access in CheckItem
a[i]=items[i].myPrice*((items[i].mySalesTax\100)+1);
This is the code I currently have.
public class CheckItem
{
private double myPrice,
mySalesTax;
private int myQuantity = 1;
public CheckItem( double price, double salesTax )
{
myPrice = price;
mySalesTax = salesTax;
}
public int getQuantity()
{
return myQuantity;
}
public void setQuantity( int qty )
{
myQuantity = qty;
}
public double lineItemTotal()
{
return roundMoney((myPrice*myQuantity)*((mySalesTax/100)+1));
}
public static double roundMoney( double amount )
{
return (int)(100 * amount + 0.5) / 100.0;
}
public static void setQuantities( CheckItem[] items, int[] quantities )
{
for (int i=0;i<quantities.length;i++){
items[i].myQuantity=quantities[i];
}
}
public static double[] lineItemTotals( CheckItem[] items )
{
double[] a=new double[items.length];
for (int i=0;i<items.length;i++){
a[i]=items[i].myPrice*((items[i].mySalesTax/100)+1);
}
return a;
}
}
The problem is that static methods can't access private instance variables. Define getters and setters for those variables, and use them:
items[i].setQuantity(quantities[i]);
a[i]=items[i].getPrice()*((items[i].getSalesTax()\100)+1);
and it will work.
This code compiles fine. If you are trying to access private members outside this class you would get private access error during compilation. In that case standard fix is to provide setters and/or getters.
** EDIT **
Seems like there is confusion about allowed access. You can NOT access any instance variables from static methods/context DIRECTLY! But you CAN access instance variables via instance itself as shown here:
class Test {
private int s = 123;
void instPrint() {
System.out.println(s); // fine
}
static void statPrint(Test ss) {
System.out.println(ss.s); // this is fine too!
// System.out.println(s); // does not compile obviously
}
}
This is the same case as in the code above. This has nothing to do with access modifiers because it's all happening in the same class.
Your code declares these two member variables in class CheckItem with the private scope. This means no other classes can access them directly on a CheckItem instance:
private double myPrice,
mySalesTax;
If you want class TC1 to be able to read or modify them, declare them in CheckItem.java as public. Alternatively, and generally a better practice, you could add public methods to CheckItem.java to allow other classes to access their values:
public double getMyPrice() {
return this.myPrice;
}
public void setMyPrice(double price) {
this.myPrice = price;
}
public double getMySalesTax() {
return this.mySalesTax;
}
public void setMySalesTax(double st) {
this.mySalesTax = st;
}
public int getMyQuantity() {
return this.myQuantity;
}
public void setMyQuantity(int newQty) {
this.myQuantity = newQty;
}
Then, in TC1.java you'd use these methods instead of direct access:
items[i].setMyQuantity(quantities[i]);
and
a[i]=items[i].getMyPrice()*((items[i].getMySalesTax()\100)+1);

Categories

Resources