我只是为项目编写代码,但是我遇到了问题,因为我需要将我的字符串乘以数字。这是我的代码部分
int shoes=50;
int shirts=30;
int shorts=75;
int caps=15;
int jackets=100;
以上是产品以及它们以美元计算的成本:
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;
这是我遇到的错误: 对于参数类型字符串int
,运算符*未定义有什么建议吗?
答案 0 :(得分:4)
您可能希望使用Map
来映射每件产品及其费用。
Map<String, Integer> productMap = new HashMap<String, Integer>();
productMap.put("shoes",50);
...
然后就这样做:
int cost= productMap.get(product)*quantity;
答案 1 :(得分:2)
您需要一种方法来查找给定产品名称的价格。一种方法是使用Map
:
Map<String,Integer> productPrices = new HashMap<String,Integer>();
这会创建一个容器,该容器将保存Integer
个值,可以使用String
查找。
然后将您的产品添加到其中:
productPrices.put("shoes", 50);
productPrices.put("shirts", 30);
等等。然后计算你的费用:
Integer cost = productPrices.get(product) * quantity;
答案 2 :(得分:1)
您需要先转换为和整数:
int stringAsInt = 0;
try{
stringAsInt = Integer.parseInt(yourStringHere);
}catch(NumberFormatException nfe){
//Log error here.
}
答案 3 :(得分:0)
您需要使用Map
以将产品类型作为输入并检索整数输出,该输出是产品类型的成本。
Map<String, Integer> products = new HashMap<String, Integer>();
products.put("shoes", 50);
并使用
检索值products.get("shoes");
您可以在HashMaps here上找到更多信息。