Trying to make code to work with this main:
// TestClass class ResselerTest {
public int ValueOfContainer(Object conatiner, carmodel) { //have to count value of Mazda cars
}
public static void main(String[] args) {
Reseller Joe = new Reseller();
//name cash in k's
Customer John = new Customer("John", 200);
John.get(new Ford(5)); // (i) no of cars. John want to buy 5 ford's
John.get(new Ferrari(5));
John.get(new Mazda(3));
ShoppingCart JohnCart = John.getShoppingCart();
System.out.println("Before payment\n" + JohnCart);
// Hes paying right now!
John.pay();
System.out.println("Paid\n" + John.getShoppingCart());
System.out.println("John got : " + John.getCash() + " USD");
// Now we need to pack them into container
Container JohnContainer = new Container(John);
janek.pack(JohnContainer);
// After packing to conainer.
System.out.println("After packing to conainer\n" + John.getShoppingCart());
// Check whats in container
System.out.println(JohnContainer);
// Lets see how much John paid for white cars.
System.out.println("White cars cost: " +
valueOf(JohnContainer, "white") );
} }
// ---------------------------------------------------------------
class Reseller {
public Reseller() {
// PriceList Singleton!!!
PriceList pl = PriceList.getInstance();
pl.set("Ford", 24);
pl.set("Ferrari", 120);
pl.set("Mazda", 9); //price in k's }
}
//---------------------------------------------------------------
public class Customer { String name; int cash;
public Customer(String name, int cash) {this.name = name; this.cash = cash;
}
public }
//---------------------------------------------------------------
public class ShoppingCart( { //public ShoppingCart // no idea
}
//---------------------------------------------------------------
public class PriceList { public static PriceList instance = null; HashMap<String, Integer> prices = new HashMap<String, Integer>();
public static PriceList getInstance() { if (instance == null) { instance = new PriceList(); } return instance; }
public void set(String car, int value){
prices.put(car, value);
}
// singleton
public PriceList() {
}
}
My main problem.
How to make John.get(new Mazda(3)); to work <sic!>
And how to link cars to color. As far was sad that 1 car have 1 color (Ferrari => ofc. Red :))
I will appreciate any help from you fellows.
It appears that get() doesn't work because you haven't written this bit yet. I suggest you try to write this method (at least the declaration)
It appears you need a structure/class which associates Car and Color.
I suggest you use camelCase for variable names.
I think there is something rather wrong with your object model.
It appears that you have a class for each model of Car. I'd have thought that where needed to be a single Car class, which had attributes such as "model", "color", "price" and so on.
It appears that an instance of (say) Ferrari is supposed to represent a number of cars, rather than a single Car.
I'm not going to tell you exactly how to implement this, since it looks like homework to me.
Well, first of all get Object Oriented concepts clear. What is a person to car relationship.
Secondly, John.get(new Mazda(3)) is not a very good program. The method names should indicate what they do. Here get method is used for actually setting the purchase made by that customer. John buys 3 Mazdas when we call John.get(new Mazda(3)) Is that understanding correct?
The advantage of OOP is that we can map real world entities and talk in real world terminologies in our program. So something like makePurchase(..), submitOrder(..), checkOut(..) would make sense.
It is often said that the programming language helps us think. (sometimes they limit our thoughts :))
Also, a good OO design will say something like a Customer class has a method:
checkOut(Set cars) instead of
checkOut(Honda[] hondaCars)
Does this help?
Related
package Car;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Car myCar = new Car();
myCar.AddDoor();
myCar.AddDoor();
}
}
class Car {
public int door = 4;
public void AddDoor() {
this.door++;
System.out.println("The car has " + door + " " + "doors");
}
}
Your requirement is to add doors without printing anything about the doors. The code you posted is doing both in one method: this.door++ as well as System.out.println(). Instead, you need two different methods. Here's a way to edit what you posted to work like you want.
Remove the System.out.println() from addDoor() (notice the lowercase first letter, that follows Java naming conventions). As you noted, you want to add a door without printing anything about the door totals. That would leave your method looking like this:
public void addDoor() {
this.door++;
}
Make a new method in your Car class, call it printDoorInfo() or some such, and move your println() code there, like this:
public void printDoorInfo() {
System.out.println("The car has " + this.door + " doors");
}
In your calling code, after you have called myCar.addDoor() as many times as you like, call your new door info printer:
myCar.printDoorInfo();
Starting of I want to apologise for my english as I'm not a native speaker. The title might be a bit off since I was not sure how to phrase it but hopefully it will come through once I show my code.
The problem I'm phasing is I want to use the shop class to handle any purchases while storing the money variable on the player class.
Is there any way to access the money integer of the player class without creating an object of the player class in the shop class ?
I was thinking about using a static integer to store the data in but from what I've read online its bad practice to use static datatypes.
public class Beta {
public static void main(String[] args) {
Player p1 = new Player("Test");
Shop s1 = new Shop();
p1.setMoney(100);
s1.clerk(p1.getMoney());
}
}
public class Player {
private int money;
private String name;
public Player(String name) {
this.name = name;
}
public int getMoney() {
return money;
}
public void setMoney(int x) {
this.money +=x;
}
}
public class Shop {
private int money;
public void clerk(int x) {
this.money = x;
if (this.money >= total) {
question4 = false;
System.out.println("Your purchase was successful!");
if (blue > 0) {
this.addInventory("Blue", blue);
}
if (red > 0) {
this.addInventory("Red", red);
}
if (green > 0) {
this.addInventory("Green", green);
}
}
else {
question4 = false;
System.out.println("Sorry you cant afford that!");
}
}
}
}
So I cut down my code to show you only the essential parts.
What I want to do is access p1:s money variable from the player class from within the Shop class.
So far I have been passing the variable when calling it from main. Is this the only option I have or can it be accessed in any other way ?
Any help would be much appreciated!
I believe the option that follows Object-Oriented Programming principles best is to pass the actual Player in as an argument, instead of just the money.
Basically, passing just the player's money in instead of the player themselves is like just handing your wallet over to the cashier. You wouldn't do that, right?
This way, the clerk can ask the customer if they have enough money by calling player.getMoney(), and the customer can tell them the answer.
After making the purchase, the player can remove the money from their wallet themselves when the clerk asks them to via player.setMoney().
Now, you asked in a comment about "passing the actual player as an argument without creating a new object of the player class." Java passes arguments by value, and all objects' values are simply the address that hold the information for that particular instance.
So for Player p1 in Beta, let's pretend all of p1's information is stored in a block starting at...let's say, address 21343. In this case, the variable p1 only contains that single number, 21343.
Since Java passes by value, then when you call s1.clerk(Player player), the player variable will also contain 21343. Since it's editing the items contained at the same address, you've essentially passed on p1 itself instead of creating a new Player. In short, the clerk and the main method work with the same object.
The fact that Java passes by value is also why passing just the player's money in doesn't adjust it automatically: The money is an int rather than an object. Since it's an int, when you pass it to the clerk, you're just saying "Hey, clerk, this is the amount of money being worked with." But the clerk has no idea who the money belongs to, so while it can take money, or even give it some, it's essentially just setting it down on the counter, and it's the responsibility of the player to pick it up from there when they're done. By passing in the player instead, the clerk knows who the money belongs to because it's actually asking the player how much money they have.
Another potential solution would be to make p1 and s1 static variables in the Beta class. It'd look something like this:
public class Player
{
public static Player p1;
public static Shop s1;
public static void main(String[] args)
{
p1 = new Player("Test");
s1 = new Shop();
p1.setMoney(100);
s1.clerk(p1.getMoney());
}
}
From there, you'd import the Beta class in Shop, then call Beta.p1 in Shop to access p1.
Hope this helps!
I do not know how to do the borrowHolding() in the Library Menu I have to create.
So the purpose of the borrowHolding() is for members to be able to borrow books or videos.
This is a just a sample data of the array:
member[0] = new StandardMember("ID", "Name");
member[1] = new PremiumMember("ID", "Name");
holding[0] = new Book("ID", "Title");
holding[1] = new Video("ID", "Title", loanFee);
This is the borrowHolding() method in the TestLibrary class: (the array is in the TestLibrary class too)
public static void borrowHolding(){
String option;
option = input.next();
do{
Scanner scan = new Scanner(System.in);
int tempId = 0;
System.out.println("Enter your ID: ");
String searchID = scan.next();
for(int i = 0; i < member.length; i++){
if(member[i].getID().equals(searchID)){
tempId = i;
}
}
So for the method, I tried to write a code that will search through the array to find the memberID that wants to borrow. It is not completed yet because I believe I am not doing it correctly
There is a Member class that contains
public class Member{
public Holding[] getCurrentHoldings(){
}
}
from the name of the method, it is used to store the holdings of the members that borrowed. So if member 1 borrows a book, that book will be stored inside the array, i think. I was thinking of using an ArrayList for this method, but not sure if it would make sense.
To borrow a book or video, there are certain conditions to be able to borrow, but I do not know how to implement this into the borrowHolding(). One of the condition are in the Holding class.
public class Holding{
public boolean borrowHolding(){
if(status == true && isOnLoan() == false)
borrowDate = newDateTime(); //this is to get the time when the book or video is borrowed
return true;
}else
return false;
}
}
And there is another condition in the Member class is that the Member must have enough credit to borrow. A book loan fee will cost $10 and a video will vary from $4 or $6.
I think I wrote a few information that is not needed but I guess its better than less information.
My problem is what do I do to the borrowHolding() method in the LibraryMenu? how do I make that if a member wants to borrow a holding, the holding will go under the member's array in the member class
public class Member{
public Holding[] getCurrentHoldings(){
}
}
with the condition from the holding class if it is met, and while executing the borrowHolding method, the method from the member class will be able to subtract the member credit by the loan fee from the book or video. is it possible?
public class Member{
private int credit = 30;
public int calculateRemainingCredit(){
credit = credit - //(the loan fee from the book or video class)
}
}
If your intentions are to add a holding to the member class then this is possible. I would suggest adding an ArrayList of Holding's rather than a regular array because it seems as if the size is going to be constantly changing.
public class Member{
private ArrayList<Holding> currentholdings; // you may need to import the arraylist
private int credit;
public void init(){ // goes in constructor
currentholdings = new ArrayList<Holding>();
credit=0;
}
public void addHolding(Holding newholding){ // adds a new holding to the members array
currentholdings.add(newholding);
credit-=newholding.getFee(); // will need to add a fee variable to the holding class;
}
}
And as for checking to see whether or not the member has enough "credit", that can be done in the borrowHolding() method right after you identify the index of the array. I would just recommend adding a parameter of the member to the borrowHolding() method so you can easily access the variables from that member.
if(member[i].getID().equals(searchID)){
tempId = i;
int tempHolding; // index of whatever holding you wanted (could get this from the scanner)
if (holding[tempHolding].borrowHolding(member[tempId])){ // check status
member[tempId].addHolding(holding[tempHolding]); // they have passed the req. so you can add the holding
}
break;
}
Hope this answered your question.
I have a player which can feed a dog or chop a tree.
Below are the classes I have written:
public class Dog {
private int health;
public void feed(Food food){
health = health + food.getNutritionalValue();
}
}
public class Player{
public void feed(Dog dog, Food food) {
dog.feed(food);
}
Player and Dog both have methods that are "active".
Player feeds the dog and dog starts eating the food (I am not really sure if it is good to couple methods in this way).
On the other hand, I have tree. And player is able to chop the tree.
public class Player{
public void chop(Tree tree) {
//At this point I am not sure
}
I am not sure if I would use getters and setters of Tree class to interact with the Tree.
Or if I should write an own method for this because the tree gets chopped so it is nothing really active I would call.
So, in the end, there would be two or more kinds of implementations but the two I am thinking of are:
tree.setAmountofWood = x
or
tree.gettingChopped(Damage int)
I think I should make an own method for this chopping-process.
Or is there any design principle I should follow?
I see 3 principles here,
SRP - It is the responsibility of the Tree to get chopped and fall down, but to cut is the responsibility of the Person!
Demeter's law - looks good from my POV.
OCP - The tree must be able to do further actions when get cut.
So you must use
tree.gettingChopped(Damage damage)
To your code:
The method Dog.feed is wrong, rename it to Dog.eat because the Dog is not feeding, the dog is eating. By the way, the food must reduce its NutritionalValue.
The health is an integer value, this is bad because in reality there is nothing like a numeral health. We may have a handicapped numeral value in percent, but this is more a byte who not can be in negative value. You should create a custom class for the Health! This way your code is open(OCP) for extensions like to be toxified or depresive.
I would start from something like this.
Tree can grow and receive damage.
public class Tree {
private int lumber;
public Tree(int size) {
this.lumber = size;
}
public void grow() {
this.lumber++;
}
public void grow(int size) {
this.lumber += size;
}
public int receiveDamage(int damage) {
int lumber = 0;
if (damage > this.lumber) {
lumber = this.lumber;
this.lumber = 0;
} else {
lumber = damage;
this.lumber -= damage;
}
return lumber;
}
}
Food just stores nutritional value.
public class Food {
private int nutrition;
public Food(int nutrition) {
this.nutrition = nutrition;
}
public int getNutritionalValue() {
return this.nutrition;
}
}
I'm not sure if all types of player can chop trees, so I created a class to separate responsibilities. You can move methods to the Player class if you like.
public class Woodcutter extends Player {
public int chop(Tree tree) {
// lumber amount may depend on a tool,
// i.e. axe, chainsaw, etc.
return tree.receiveDamage(10);
}
// fell down the tree
public int fell(Tree tree) {
int result = 0;
int lumber = 0;
do {
lumber = chop(tree);
result += lumber;
} while (lumber > 0);
return result;
}
}
Somewhere in your code
// create a tree and let it grow for a while
Tree tree = new Tree(10);
tree.grow(90);
// Start chopping
Woodcutter woodcutter = new Woodcutter();
System.out.println("Lumber received: " + woodcutter.chop(tree));
System.out.println("Lumber received: " + woodcutter.fell(tree));
Dog dog = new Dog();
Food food = new Food(5);
woodcutter.feed(dog, food);
I wouldn't dive into passive/active methods here. An 'active tree' may indeed be a misnomer.
I would rather consider calling an object's method as passing a message to the object. And you apparently need to send the message to the tree that it is currently being cut by someone, and let the tree decide when to e.g. fall() or to bend(), or to shake().
The tree has some internal state (strength? thickness of its trunk? health?). 'Sending a message' to the tree means to call its method, e.g. beingCut(), which in turn deteriorates the state of the tree. After the state of the tree reaches a certain limit, other actions (=consequences of tree's bad state) may be started by the tree.
Of course, as in every iteration of your main loop you tree has also the chance to get the message to grow(), so its state may improve a little each time, so eventually it may even recover from being only partially cut and reach its initial, perfect state back.
So, yes, while trees seem rather passive, they still react to messages/stimulus. :-)
I'm just getting started in Java and am looking for advice on a good way to store nested sets of data. For example, I'm interested in storing city population data that can be accessed by looking up the city in a given state. (Note: eventually, other data will be stored with each city as well, this is just the first attempt at getting started.)
The current approach I'm using is to have a StateList Object which contains a HashMap that stores State Objects via a string key (i.e. HashMap<String, State>). Each State Object contains its own HashMap of City Objects keyed off the city name (i.e. HashMap<String, City>).
A cut down version of what I've come up with looks like this:
// TestPopulation.java
public class TestPopulation {
public static void main(String [] args) {
// build the stateList Object
StateList sl = new StateList();
// get a test state
State stateAl = sl.getState("AL");
// make sure it's there.
if(stateAl != null) {
// add a city
stateAl.addCity("Abbeville");
// now grab the city
City cityAbbevilleAl = stateAl.getCity("Abbeville");
cityAbbevilleAl.setPopulation(2987);
System.out.print("The city has a pop of: ");
System.out.println(Integer.toString(cityAbbevilleAl.getPopulation()));
}
// otherwise, print an error
else {
System.out.println("That was an invalid state");
}
}
}
// StateList.java
import java.util.*;
public class StateList {
// define hash map to hold the states
private HashMap<String, State> theStates = new HashMap<String, State>();
// setup constructor that loads the states
public StateList() {
String[] stateCodes = {"AL","AK","AZ","AR","CA","CO"}; // etc...
for (String s : stateCodes) {
State newState = new State(s);
theStates.put(s, newState);
}
}
// define method for getting a state
public State getState(String stateCode) {
if(theStates.containsKey(stateCode)) {
return theStates.get(stateCode);
}
else {
return null;
}
}
}
// State.java
import java.util.*;
public class State {
// Setup the state code
String stateCode;
// HashMap for cities
HashMap<String, City> cities = new HashMap<String, City>();
// define the constructor
public State(String newStateCode) {
System.out.println("Creating State: " + newStateCode);
stateCode = newStateCode;
}
// define the method for adding a city
public void addCity(String newCityName) {
City newCityObj = new City(newCityName);
cities.put(newCityName, newCityObj);
}
// define the method for getting a city
public City getCity(String cityName) {
if(cities.containsKey(cityName)) {
return cities.get(cityName);
}
else {
return null;
}
}
}
// City.java
public class City {
// Define the instance vars
String cityName;
int cityPop;
// setup the constructor
public City(String newCityName) {
cityName = newCityName;
System.out.println("Created City: " + newCityName);
}
public void setPopulation(int newPop) {
cityPop = newPop;
}
public int getPopulation() {
return cityPop;
}
}
This is working for me, but I'm wondering if there are gotchas that I haven't run into, or if there are alternate/better ways to do the same thing.
(P.S. I know that I need to add some more error checking in, but right now, I'm focused on trying to figure out a good data structure.)
(NOTE: Edited to change setPop() and getPop() to setPopulation() and getPopulation() respectively to avoid confucsion)
If you really need these kinds of aggregation (StaleList that have States, States that have Cities), then this is the correct way to implement. It may not be the most straightforward, but it is the most object oriented approach. So, for the cost of minimalism, you sure get cohesion, coupling, maintainability and all those fancy software engineering adjectives. For small projects, these characteristics should not be enforced. But for big software projects they make sense and avoid really bad code (but do not guarantee really good code).
You can also use some third-party libraries (like the one from Pangea answer) to help keeping the code simple.
See:
1: http://en.wikipedia.org/wiki/Cohesion_(computer_science)
2: http://en.wikipedia.org/wiki/Coupling_(computer_science)
3: http://en.wikipedia.org/wiki/Maintainability
Checkout the Multimap data structure from guava collections. This is not the complete answer to your solution but will simplify to certain level. But the beauty is that now you can use MapMaker to cache your "population queries" against the city.
Multimap<String, City> stateToCities = ArrayListMultimap.create();
stateToCities.put("GA",new City("Atlanta",100000));
stateToCities.put("GA",new City("Cumming",50000));
I would consider using one class to manage a list States containing member variables of City and population in two-dimensional arrays.
Other thoughts:
cityAbbevilleAl is not checked against null.
At first, I misread getPop as a pop method and not population.
Spell out "population". Key strokes are cheap. You've already confused one responser here; it's likely that others won't get it at first, either.
Can population be negative? If not, I'd check that in your contract for setPopulation().