-4

I was just writing code for project that's due for class but I'm having a problem because I need to multiply my string with a number. Here's parts of my code

int shoes=50;
int shirts=30;
int shorts=75;
int caps=15;
int jackets=100;

Those above are the products and how much they cost in dollars:

    System.out.print("Enter the product: ");
String product=keyboard.nextLine();
System.out.print("Enter the quantity of the product");
int quantity=keyboard.nextInt();    
System.out.print("cost= +product+*+quantity+");
int cost= product*quantity;

This is the error I'm having: The operator * is undefined for the argument type(s) string, int

Any suggestions?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
user3394363
  • 53
  • 3
  • 6

4 Answers4

4

You may want to use a Map to map each product with its cost.

Map<String, Integer> productMap = new HashMap<String, Integer>();
productMap.put("shoes",50);
...

And then just do:

int cost= productMap.get(product)*quantity;
Alexis C.
  • 91,686
  • 21
  • 171
  • 177
2

You need a way to look up a price given a product name. One way is using a Map:

Map<String,Integer> productPrices = new HashMap<String,Integer>();

This creates a container that will hold Integer values that can be looked up using a String.

Then add your products to it:

productPrices.put("shoes", 50);
productPrices.put("shirts", 30);

and so on. Then to calculate your cost:

Integer cost = productPrices.get(product) * quantity;
Mike B
  • 5,390
  • 2
  • 23
  • 45
1

You need to convert to and integer first:

int stringAsInt = 0;
try{
  stringAsInt  = Integer.parseInt(yourStringHere);
}catch(NumberFormatException nfe){
  //Log error here.
}
user2793390
  • 741
  • 7
  • 29
0

You will want to use a Map in order to take the product type as an input and retrieve an integer output that is the cost of the type of product.

Map<String, Integer> products = new HashMap<String, Integer>();
products.put("shoes", 50);

and retrieve the value using

products.get("shoes");

You can find more on HashMaps here.

TronicZomB
  • 8,667
  • 7
  • 35
  • 50