Reputation: 1
I want to add some item from the class DisplayCard
to the hashMap displayCardMap
by the method.
The output of hashmap to look like
brand: modelNumber: memorySize
Then I create some method to help me.
import java.util.*;
public class ComputerShop {
Map <String, Double> displayCardMap = new HashMap <String, Double>();
public void addDisplayCard(DisplayCard oneDisplayCard){
displayCardMap.put(oneDisplayCard.getBrand() + ": " + oneDisplayCard.getmodelNumber(), oneDisplayCard.getmemorySize());
}
}
public class DisplayCard {
String brand;
String modelNumber;
double memorySize;
//constructor method
public DisplayCard(String brand, String modelNumber, double memorySize){
this.brand = brand;
this.modelNumber = modelNumber;
this.memorySize = memorySize;
}
// getter method
public String getBrand(){
return brand;
}
public String getmodelNumber(){
return modelNumber;
}
public double getmemorySize(){
return memorySize;
}
}
But I get an error after I create a new item by the addDisplayCard()
public class TestComputerShop{
public static void main(String[] args) {
ComputerShop ashop = new ComputerShop();
// call method
ashop.addDisplayCard("ATI", "R9 390",6.0);
}
}
So I want to know what is the problem.
Should I create a new DisplayCard
object first? Or the function is wrong at the beginning.
Upvotes: 0
Views: 49
Reputation: 3966
you need to create a new DisplayCard
object, because your method requires one:
public class TestComputerShop {
public static void main(String[] args) {
ComputerShop ashop = new ComputerShop();
// call method
ashop.addDisplayCard(new DisplayCard("ATI", "R9 390",6.0));
}
}
Another solution is to use method overloading inside the ComputerShop
:
public class ComputerShop {
Map <String, Double> displayCardMap = new HashMap <String, Double>();
public void addDisplayCard(DisplayCard oneDisplayCard){
displayCardMap.put(oneDisplayCard.getBrand() + ": " + oneDisplayCard.getmodelNumber(), oneDisplayCard.getmemorySize());
}
public void addDisplayCard(String brand, String modelNumber, double memorySize){
this.addDisplayCard(new DisplayCard(brand, modelNumber, memorySize));
}
}
Upvotes: 2