繁体   English   中英

如何制作和更新Java中的方法?

[英]How do I make and update method in java?

我需要能够在此代码部分中非常简单地更新数量:

import java.util.HashMap;
import java.util.Map;


public class StockData {

private static class Item {
    Item(String n, double p, int q) {
        name = n;
        price = p;
        quantity = q;
    }

    // get methods
    public String getName() { return name; }
    public double getPrice() { return price; }
    public int getQuantity() { return quantity; }

    // instance variables 
    private String name;
    private double price;
    private int quantity;
}

// with a Map you use put to insert a key, value pair 
// and get(key) to retrieve the value associated with a key
// You don't need to understand how this works!
private static Map<String, Item> stock = new HashMap<String, Item>();

static {
    // if you want to have extra stock items, put them in here
    // use the same style - keys should be Strings
    stock.put("00", new Item("Bath towel", 5.50, 10));
    stock.put("11", new Item("Plebney light", 20.00, 5));
    stock.put("22", new Item("Gorilla suit", 30.00, 7));
    stock.put("33", new Item("Whizz games console", 50.00, 8));
    stock.put("44", new Item("Oven", 200.00, 4));
}

public static String getName(String key) {
    Item item = stock.get(key);
    if (item == null) return null; // null means no such item
    else return item.getName();
}

public static double getPrice(String key) {
    Item item = stock.get(key);
    if (item == null) return -1.0; // negative price means no such item
    else return item.getPrice();
}

public static int getQuantity(String key) {
    Item item = stock.get(key);
    if (item == null) return -1; // negative quantity means no such item
    else return item.getQuantity();
}

// update stock levels
// extra is +ve if adding stock
// extra is -ve if selling stock
public static void update(String key, int extra) {
    Item item = stock.get(key);
    if (item != null) item.quantity += extra;
}

}

我已经为更新页面构建了GUI,只需要添加方法即可?

对不起这个琐碎的问题,但您必须从某个地方开始。

谢谢你的帮助。

我不知道我是否真的遇到您的问题,但这是我建议增加您物品的数量。

只需添加一个像这样的公共方法:

public void addQuantity(int q) { quantity += q }

我希望你是这个意思。

添加此方法:

公共无效setQuantity(int q){数量= q}

您可能想开始阅读http://docs.oracle.com/javase/tutorial/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM