有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将NumberFormat对象传递给方法?

我正在尝试使用NumberFormat对象来显示价格。我对编程非常陌生,我的书没有多大帮助,我的老师也没有。我有一个叫做Product的类和一个叫做MyProduct的类,这是Product的一个子类。在Product类中有一个名为getPrice()的方法,它没有参数。它所做的只是按价格返回值。我的任务是在MyProduct中创建一个名为getPrice(NumberFormat nf)的方法,该方法返回价格,但格式为货币。在主要方法中,如果我使用myproduct。getPrice();我得到了价格,但没有格式化(我知道这是因为它从Product调用getPrice(),而不是从MyProduct调用getPrice(NumberFormat nf)。我的问题是,我应该用什么作为参数来阻止编译时错误?我试过getPrice(nf)、getPrice(this)、getPrice(price),几乎任何我能想到的东西都没用。如有任何帮助,我们将不胜感激,所有相关代码将发布在下面。提前谢谢

下面是MyProduct类

public class MyProduct extends Product{
public MyProduct()
{
 super();
}

NumberFormat nf;

public String getPrice(NumberFormat nf) {

    this.nf = NumberFormat.getCurrencyInstance();
    String priceFormatted = nf.format(price);
    return priceFormatted;
}

下面是ProductApp类

public class ProductApp {

public static void main(String args[]) {
    // display a welcome message
    System.out.println("Welcome to the Product Viewer");
    System.out.println();

    // create 1 or more line items
    Scanner sc = new Scanner(System.in);
    String choice = "y";
    while (choice.equalsIgnoreCase("y")) {
        // get input from user
        System.out.print("Enter product code: ");
        String productCode = sc.nextLine();

        // Use a ProductReader object to get the Product object
        ProductDB db = new ProductDB();            

             MyProduct myproduct = db.getProduct(productCode);

        // display the output
        String message = "\nPRODUCT\n" +
            "Code:        " + myproduct.getCode() + "\n" +
            "Description: " + myproduct.getDescription() + "\n" +
            "Price:       " + myproduct.getPrice()+ "\n";
        System.out.println(message);

        // see if the user wants to continue
        System.out.print("Continue? (y/n): ");
        choice = sc.nextLine();
        System.out.println();
    }
    System.out.println("Bye!");

我需要帮助的是

"Price:       " + myproduct.getPrice()+ "\n";

共 (1) 个答案

  1. # 1 楼答案

    当您在getPrice方法中实例化nf时,我不会费心传递它。可能会将方法名称更改为getPriceAsString之类的名称,定义为

    public String getPriceAsString() {
    
        NumberFormat nf = NumberFormat.getCurrencyInstance();  // keep local
        String priceFormatted = nf.format(price);
        return priceFormatted;
    }
    

    然后你可以叫它myProduct.getPriceAsString ()

    编辑

    根据你的评论

    主要做什么

    "Price:       " + myproduct.getPrice(NumberFormat.getCurrencyInstance())+ "\n";
    

    并将该方法声明为

    public String getPrice(NumberFormat nf) {
        return nf.format(price);
    }
    

    我假设price设置正确