java - java存储实例变量并使用键值之一进行访问
问题描述
我目前正在uni中学习Java,遇到了这个问题:
public class simpleStockManager {
private String sku;
private String name;
private double price;
public void newItem(String sku, String name, double price) {
this.sku = sku;
this.name = name;
this.price = price;
}
public String getItemName(String sku) {
return name;
}
}
我已经声明了一个类和一些实例变量,并尝试使用sku
. 因此,如果我按此顺序声明 3 个项目:
simpleStockManager sm = new simpleStockManager();
sm.newItem("1234", "Jam", 3.25);
sm.newItem("5678", "Coffee", 4.37);
sm.newItem("ABCD", "Eggs", 3.98);
当我尝试使用它的getItemName
方法时,sku == "5678"
它应该返回"Coffee"
,但它正在返回"Eggs"
。我认为这是覆盖前一个项目的最新声明项目,但我不知道如何解决这个问题。任何帮助将不胜感激。
解决方案
每次调用都会newItem
更改实例变量的值。
您将始终获得由m.newItem("ABCD", "Eggs", 3.98);
如果您想使用sku作为键来存储多个变量,您可以使用Map
例如 :
class SimpleStockManager{
// The key of your map will be sku,
//and the name and the price can be for exemple in a Product class
private HashMap<String, Product> products = new HashMap<>();
public void newItem(String sku, String name, double price){
// A call to newItem will create a new Product and store it
products.put(sku, new Product(name, price));
}
public String getItemName(String sku){
if (products.containsKey(sku)){
return products.get(sku).getName();
}else {
return " Product not found...";
}
}
}
推荐阅读
- react-native - 如何使用试剂从其他文件中正确导入组件?
- javascript - Kibana 不显示从 Node.js Winston Logger 发送到 Elasticsearch 的日志
- php - 如果我使用 AWS RDS 将用户输入存储到数据库中,我的 PHP 文件应该放在哪里?
- java - 如何跟踪 Java 异常
- python - 在 Tkinter 中,有没有办法在运行程序时停止执行回调函数?
- c++ - 我如何计算向量[5][1] N 次
- json - Ionic - 带有 laravel json 响应的 API
- javascript - 如何使用 JS 控制 CSS 过渡和动画?
- c++ - 如何将按位运算符与 unsigned char 数据类型一起使用?
- python - 替换 np.array 中元素的更快方法