I have a class car with constructor as
public car (String name, int numberOfCars, int price) {}
Then, in my main, I created stack as:
Stack<car>carStack = new Stack<car>();
carStack.push("Honda", 200, 19000));
carStack.push("Toyota", 300, 18000));
carStack.push("BMW", 150, 40000));
How can I get the price of 500 cars (150 BMW + 300 Toyota + 50 Honda) from this stack?
Steps:
Iterate through the Stack with a for loop. Stack implements the Iterable interface, and so a for-each loop is probably the easiest to use: for (Car myCar: carStack) {...}
call getPrice() on the items in the loop
add this to a sum variable that has been declared before the loop
Q.E.D.
As an aside, to have your code comply with Java naming standards, your car class should be renamed Car. Class and interface names should begin with an upper case letter.
Since someone else is showing off code, here's my big whoop code snippet:
double price = 0.0;
for (Car myCar: carStack) {
price += myCar.getPrice();
}
You can iterate your stack within a foreach-loop:
double price = 0.0;
for(Car c : stack)
{
price += c.getPrice();
}
Or you can iterate your stack within a while-loop:
Iterator<Car> iter = carStack.iterator();
double price = 0.0;
while (iter.hasNext()) {
price += iter.next().getPrice();
}
If you're using Eclipse Collections, you can use a MutableStack which has the method sumOfInt().
Car honda = new Car("Honda", 19000);
Car toyota = new Car("Toyota", 18000);
Car bmw = new Car("BMW", 40000);
MutableStack<Car> carStack =
ArrayStack.newStackFromTopToBottom(honda, toyota, bmw);
long price = carStack.sumOfInt(new IntFunction<Car>()
{
#Override
public int intValueOf(Car eachCar)
{
return eachCar.getPrice();
}
});
Assert.assertEquals(77000, price);
The question mentions that each car has a number of occurrences. Perhaps a Bag would be a more appropriate data structure than a StackIterable. A Bag keeps track of items and how many times the item occurs in the Bag. It would mean deleting the numberOfCars field from Car.
MutableBag<Car> carBag = HashBag.newBag();
carBag.addOccurrences(honda, 200);
carBag.addOccurrences(toyota, 300);
carBag.addOccurrences(bmw, 150);
long price = carBag.sumOfInt(new IntFunction<Car>()
{
#Override
public int intValueOf(Car eachCar)
{
return eachCar.getPrice();
}
});
Assert.assertEquals(15200000, price);
When Java 8 is released, we can replace the anonymous inner class with a lambda or method reference. Here's what the code will look like with a method reference.
long price = carBag.sumOfInt(Car::getPrice);
If price were a double instead of an int, we'd just need to replace sumOfInt() with sumOfDouble().
long price = carBag.sumOfDouble(Car::getPrice);
Note: I am a committer for Eclipse collections.
int total = 0;
while(!cars.isEmpty()) {
total += cars.pop().getTotal();
}
Then Car's getTotal:
public double getTotal() {
return price * quantity;
}
Or if you want to preserve stack, do the foreach that others have mentioned.
Related
I want to just take the data from menSize and its price but it keep printing out the womenSize eventhought it doesn't add anything in it.
Do I need to seperate menSize class and womenSize class or is there any way to fix it:
Here is my Getter and Setter of Shoes class:
private double menSize;
private double price;
private double womenSize;
This is my ShoesController class:
#GetMapping("menshoes")
public List getMenShoes() {
List<Shoes> menShoesList = new ArrayList<>(); // Create ArrayList holding men sizes
while (true) {
for (double i = 2; i <= 12; i += 0.5) { // set sizes : 2 , 2.5 ,... until 12
Shoes shoe = new Shoes();
shoe.setMenSize(i);
shoe.setPrice(4); // Set price to $4
menShoesList.add(shoe); // add size to ArrayList
}
return menShoesList;
}
}
#GetMapping("womenshoes")
public List<Shoes> getWomenShoes() {
List<Shoes> womenShoesList = new ArrayList<>(); // Create ArrayList holding women sizes
while (true) {
for (double i = 5; i <= 12; i += 0.5) { // set sizes : 5, 5.5 , ... until 12
Shoes shoe2 = new Shoes();
shoe2.setWomenSize(i);
shoe2.setPrice(4); // Set price to $4
womenShoesList.add(shoe2); // add size to ArrayList
}
return womenShoesList;
}
}
The output when I search for localhost:8080/menshoes are (I just take 3 for examples):
[{"menSize":2.0,"price":"$4.00","womenSize":0.0},{"menSize":2.5,"price":"$4.00","womenSize":0.0},{"menSize":3.0,"price":"$4.00","womenSize":0.0}
I see 2 options: Either having 2 classes, one for each type of shoe
or defining the type inside your class and not having two sizes of which one is always empty. Since you have a limited amount of possible types I suggest you use an enum for modeling the type.
public enum ShoeType {
MEN,
WOMEN
}
public class Shoe {
private ShoeType type;
private double size;
private double price;
// getter, setter, constructor...
}
Example of this comment:
"I would highly recommend only having one [class] type similar to what you suggested"
Default constructor
public class Shoes
{
this(null, 0, 0);
}
Overloaded constructor
public class Shoes(String gender, double size, double price)
{
this.gender = gender;
this.size = size;
this.price = price;
}
This problem has been bugging me for the last while.. i cant seem to be able to update the stock value of the vehicle that i'm selling. I understand how to search the array and locate the model that the user is looking for but i don't understand how to update the number of that specific model vehicle that are in stock. which is going to be stock - 1 after a purchase.
I have both basic getters and setters for model and stock variables in the Vehicles superclass
Any help is appreciate!
Below is the method of purchasing a car from the driver class
public void purchaseCar()
{
Scanner scan = new Scanner(System.in);
String model, ans;
System.out.println("****Car Purchase Page****");
System.out.println("Enter the model of car you're looking to purchase");
model = scan.nextLine();
for (Vehicles v : list) {
if (v.getmodel().equals(model))
{
System.out.println("Is this the model you want to purchase?");
ans = scan.nextLine();
if (ans.equals("yes")) {
System.out.println("Okay! Your order is being processed");
Vehicles.setStock() = stock - 1;
}
else {
System.out.println("not working");
}
}
}
}
You're almost there.
Change:
Vehicles.setStock() = stock - 1;
to:
v.setStock(v.getStock() - 1);
As clarification, this is the same as:
int stock = v.getStock(); // Get the current stock value of 'v'
int newStock = stock - 1; // The new stock value after the purchase
v.setStock(newStock); // Set the new stock value
You are not invoking the Vehicles.setStock() on the object you want to update. And in addition this method doesn't receive any parameter to update the new stock.
You should call the method on the instance you want to update passing it the new value of the stock.
Try this
v.setStock(v.getStock() - 1);
If it seems strange to you to use the v.getStock() to build the parameter you can create a new method within your vehicle class.
class Vehicles{
int stock;
public void consumeOne(){
stock = stock -1;
}
}
And then you can call this new method in the for statement
for (Vehicles v : list) {
if (v.getmodel().equals(model)){
ans = scan.nextLine();
if (ans.equals("yes")) {
v.consumeOne();
}else {
System.out.println("not working");
}
}
}
the question is the same as in the title. i have arraylist to which i add incomes or expenses both in form of a object. will this loop sum up all elements, and is there a better way of doing this :?
public void sumOfAllExpAndIn(){
int tmp = 0;
for (Iterator<Object> it = database.iterator(); it.hasNext();){
if (it.next() instanceof Expenses){
Expenses excalc = new Expenses();
excalc = (Expenses) it.next();
tmp -= excalc.value;
}
else {
incomes incalc =new incomes();
incalc = (incomes) it.next();
tmp += incalc.value;
}
}
System.out.format("the overall balance is %d",tmp);
}
Yes there are several better ways of doing it.
Firstly, I don't suggest you declare it as an Object list. Better is to declare an interface and then implement the interface in each of your classes:
interface BudgetValue {
double getValue();
}
class Expense implements BudgetValue {
public double getValue() {
return -value;
}
}
class Income implements BudgetValue {
public double getValue() {
return +value;
}
}
Then you can declare list of BudgetValues rather than Objects as the input to your method:
double sumBudgetValues(List<BudgetValues> budgetValues) {
}
There are two easy ways of summing them:
double total = 0.0;
for (BudgetValue value: budgetValues) {
total += value.getValue();
}
return total;
or using Java 8:
return budgetValues.stream()
.mapToDouble(BudgetValue::getValue)
.sum().orElse(0.0);
The streams method makes a lot more sense to me and allows it to be easily multithreaded if you have a lot of values to sum by turning it into a parallel stream.
There are some rare occassions where instanceof is justified but, as a rule of thumb, if you find yourself using it then start by asking yourself whether there's an interface missing.
I suggest making your Expenses and Incomes classes implement a common interface, for example LineItem. Now if you use signed values (positive for incomes and negatives for expenses), you only have to call getValue() on any implementation of LineItem and add it to your running total... no if/else needed, no collection of Object needed.
public void sumOfAllExpAndIn(){
int tmp = 0;
for (Iterator<LineItem> it = database.iterator(); it.hasNext();){
tmp += it.next().getValue();
}
}
System.out.format("the overall balance is %d",tmp);
}
I have a problem with the modification or more like assignment of an object which is passed to sub-methods. There is a Cost object, which only has some double variables to hold certain values.
public class Cost {
double insertCost = 0;
double deleteEleCost = 0;
private void addInsertCost(double cost) {
insertCost += checkCost(cost);
}
private void addDeleteCost(double cost) {
deleteEleCost += checkCost(cost);
}
public double getInsertCost() {
return insertCost;
}
public double getDeleteCost() {
return deleteEleCost;
}
public double getTotalCost() {
return insertCost + deleteEleCost;
}
}
In The following after calcAverageCost() is finished, the values of Cost cost are always 0, although in the method calcAverageCost() the values for the passed Cost object are greater than 0 (calculated):
private Cost handleCase1(Content content1, Content content2, Cost cost) {
calcAverageCost(content1, content2, cost);
System.out.println("insert: " + cost.getInsertCost());
System.out.println("delete: " + cost.getDeleteCost());
return cost;
}
In calcAverageCost() the Method getCost() calculates cost based on the two Content objects. For the example, those are not important, the thing is, that the new 6 single Cost objects for every aspect of the two Contents do in fact carry some values for insertCost and deleteCost each after puttung them into getCost().
These 6 smaller Cost objects get merged into 3 bigger ones. Even those hold values as expected.
As a final step, getMinCost() (see at the end) returns the one Cost object with the smallest costvalues and assigns this to the new Cost object finalCost. Then, this object is assigned to the passed Cost object (cost) from above. Even after those two actions, the modified double variables are printed out nicely for finalCost as well as Cost cost. But when the method calcAverageCost() ends and the method from above handleCase1() continues, the passed Cost cost once again only contains 0s in there variables, like nothing happened during the alteration in calcAverageCost().
From my understanding, there should be one internal object in Java, which is the result of the getMinCost() method. By assigning finalCost to it, this internal object is pointed at from that one Cost object. And by doing the same for Cost cost, this one should point there too. But somehow, this effect doesn't carry over to the original caller method? Do I have a misconception here? I thought this was like how Java worked.
I remember a balloon thread here on Stackoverflow, as well as many other threads regarding pass-by-value and Java. Normally I try to just read threads, this is the first time I can't wrap my head around a problem, so I dediced to ask the question...
I would really appreciate any help, and sorry if this question is a bad question.
private void calcAverageCost(Content content1, Content content2, Cost cost){
Cost min_min = new Cost();
Cost min_max = new Cost();
Cost avg_min = new Cost();
Cost avg_max = new Cost();
Cost max_min = new Cost();
Cost max_max = new Cost();
getCost(content1, content2,min_min);
getCost(content1, content2,min_max);
getCost(content1, content2,avg_min);
getCost(content1, content2,avg_max);
getCost(content1, content2,max_min);
getCost(content1, content2,max_max);
System.out.println("step1");
printCost(min_min);
printCost(min_max);
printCost(avg_min);
printCost(avg_max);
printCost(max_min);
printCost(max_max);
//These one prints out nicely
Cost s_min = new Cost();
Cost s_avg = new Cost();
Cost s_max = new Cost();
s_min.addInsertCost((min_min.getInsertCost()+min_max.getInsertCost())/2d);
s_min.addDeleteCost((min_min.getDeleteCost()+min_max.getDeleteCost())/2d);
s_avg.addInsertCost((avg_min.getInsertCost()+avg_max.getInsertCost())/2d);
s_avg.addDeleteCost((avg_min.getDeleteCost()+avg_max.getDeleteCost())/2d);
s_max.addInsertCost((max_min.getInsertCost()+max_max.getInsertCost())/2d);
s_max.addDeleteCost((max_min.getDeleteCost()+max_max.getDeleteCost())/2d);
System.out.println("step2");
printCost(s_min);
printCost(s_avg);
printCost(s_max);
//These one prints out nicely as well
Cost finalCost = getMinCost(getMinCost(s_min,s_avg),s_max);
printCost(finalCost);
//Also this one prints out nicely
cost = finalCost;
printCost(cost);
//Even this one prints out nicely
}
Here is the getMinCost() method, it just compares two Cost objects and returns the one with the better variables
private Cost getMinCost(Cost cost1, Cost cost2) {
Cost cost = cost1;
System.out.println("cost1:"+cost1.getTotalCost());
System.out.println("cost2:"+cost2.getTotalCost());
if (cost1.getTotalCost() < cost2.getTotalCost()) {
cost = cost1;
System.out.println("cost1smaller");
} else if (cost1.getTotalCost() > cost2.getTotalCost()) {
cost = cost2;
System.out.println("cost2smaller");
} else if (cost1.getTotalCost() == cost2.getTotalCost()) {
if (cost1.getDeleteCost() < cost2.getDeleteCost()) {
cost = cost1;
System.out.println("cost1delsmaller");
} else if (cost1.getDeleteCost() > cost2.getDeleteCost()) {
cost = cost2;
System.out.println("cost2delsmaller");
} else if (cost1.getDeleteCost() == cost2.getDeleteCost()) {
cost = cost1;
System.out.println("cost1deleq");
}
}
System.out.println("cost:"+cost.getTotalCost());
//shows correct result so far, the minimum cost
return cost;
}
If you want to mimic "pass by reference" behavior, in order to modify the input cost, use a holder mutable object:
public class Holder<T> {
private T value;
public void setValue(T value) {this.value = value;}
public T getValue() {return this.value;}
}
And have:
private void calcAverageCost(Content content1, Content content2, Holder<Cost> holder) {
...
holder.setValue(finalCost);
}
Or, since there is only one parameter to change:
private Cost calcAverageCost(Content content1, Content content2, final Cost cost) {
...
return finalCost;
}
And use the returned value from calling code. This would be better (you should avoid mutating the parameters of a method).
I am doing this Java assignment for hours and stuck with this tester class for very almost 5 hours.
In this assignment, I have created a Product class, a Money class, a LineItem class and an Inventory class. Now i need to create a test class to test the program by putting new lineitems into the inventory array.
In the tester class, I am trying to create a static method public static void addTestItems(Inventory theInventory) which suppose to add 4 items. For each item I will need to create a product object followed by a LineItem object to contain the newly created product. next i need to use a method from the inventory class to add the items into the array in the inventory class.
What i have tried too so far:
private static void addTestItems(Inventory theInventory)
{
Inventory[] _items;
Product product1 = new Product("Book","Objects first with Java"," An excellent introductory Java textbook");
Product product2 = new Product("CD","The dark side of the moon","The all-time classic Pink Floyd album");
Product product3 = new Product("DVD", "Transformers","Robots in disguise");
Product product4 = new Product("Laptop","Lenovo T42","A good yet affordabble laptop");
Money unitPrice1 = new Money(29,99);
Money unitPrice2 = new Money(4,99);
Money unitPrice3 = new Money(9,99);
Money unitPrice4 = new Money(450,0);
_items[0] = new LineItem(product1,5,unitPrice1);
_items[1] = new LineItem(product2,8,unitPrice2);
_items[2] = new LineItem(product3,200,unitPrice3);
_items[3] = new LineItem(product4,9,unitPrice4);
}
The current error is incompatible types- found LineItem but expected Inventory so i tried changing Inventory[] _items; to LineItem[] _items;. But the error was variable _items may not be initialise.
Sorry guys I am a real noob in Java, I tried searching on-line for ages but I do not quite understand most results. The only one i understand was http://forums.devshed.com/java-help-9/bluej-compiler-error-cannot-find-symbol-variable-object-688573.html but i tired putting into my context but failed. I also found lot of results but they had constructors and instance variables in them which my teacher specifically mentioned that I will not need them.
Wonder if expert could guide me along like let me know my mistakes. Thanks thanks.
The inventory class:
/**
* In the Inventory class, it is merely to create a list / array of product which allows the information from the linitem to be put with an index.
* For example, for the first product, we can use the inventory class to input it into the index 1. and he next product into index 2 and so on.
* It is suse to create an array and inputing the lineitem information into it.
*
* #author (your name)
* #version (a version number or a date)
*/
public class Inventory
{
// instance variables - replace the example below with your own
private LineItem[] _items;
private int _numItems;
/**
* Constructor for objects of class Inventory
*/
public Inventory()
{
// initialise instance variables
_items = new LineItem[1000];
_numItems = 0;
}
/**
* An example of a method - replace this comment with your own
*
* #param y a sample parameter for a method
* #return the sum of x and y
*/
public void addItem(LineItem item)
{
_items[_numItems]= item;
_numItems++;
}
public String toString()
{
String result="";
int i=0;
while (i < _numItems)
{
result = result + _items[i] + "/n";
i++;
}
return result;
}
public void print()
{
String myResult=this.toString();
System.out.println(myResult);
}
public Money getTotalValue()
{
int i=0;
Money total= new Money(0);
while (i<_items.length)
{
total = total.add(Money.NO_MONEY);
i++;
}
return total;
}
public LineItem getItem(String productName)
{
int i = 0;
LineItem itemDetails = null;
while (i<_items.length)
{
if (_items[i].equals(productName))
{
itemDetails= _items[i];
}
else
{
//do nothing
}
i++;
}
return itemDetails;
}
}
I have yet to comment on the methods yet but will do so once i understand it.
Your array is of type Inventory[] - but you're trying to assign references of type LineItem. You're also not initializing it. Change this:
Inventory[] _items;
to this:
LineItem[] _items = new LineItem[5];
And all should be well - although you're not using index 0 (which is why you need it to be size 5) and you're not doing anything with the array afterwards either...
Another alternative to using an array is to use a List:
List<LineItem> items = new ArrayList<LineItem>();
items.add(new LineItem(product1, 5, unitPrice1));
items.add(new LineItem(product2, 8, unitPrice2));
items.add(new LineItem(product3, 200, unitPrice3));
items.add(new LineItem(product4, 9, unitPrice4));
... next think about what you actually want to do with the items variable.
LineItem[] _items = new LineItem[4];
then the index starts from 0 not from 1,
_items[4]
will return indexoutofbounds error
A few things:
incompatible types- found LineItem but expected Inventory
is caused by the fact that your array is supposed to contain Inventory objects but you're assigning LineItems to it instead
variable _items may not be initialise
means that you have your _items object but you haven't initialized it to anything. You want to do
LineItem[] _items = new LineItem[4];
PS: If you want dynamically sized arrays, don't know how many line items you'll potentially load, etc etc use a vector or a collection or something along those lines.
Also,
_items[1] = new LineItem(product1,5,unitPrice1);
_items[2] = new LineItem(product2,8,unitPrice2);
_items[3] = new LineItem(product3,200,unitPrice3);
_items[4] = new LineItem(product4,9,unitPrice4);
In Java, array elements start with index 0 and not 1
_items
is a wonky variable name that makes your team mates sneeze in your coffee