在一个类中使用函数,始终返回 NullPointerException 错误 – Java

huangapple go评论114阅读模式
英文:

Using functions in a class keeps returning NullPointerException error - Java

问题

以下是翻译好的部分:

我遇到了一个奇怪的问题,我的类中的函数不断返回 NullPointerException。以下是我的代码,我在代码中引用了 cashRegister 类,每次我使用函数(cashRegister.add()cashRegister.toString())时,它都返回 NullPointerException。有人知道如何解决吗?

private void sell() {
    Product product = product(readName());
    System.out.println("销售:" + product.getName());
    int number = readNumber();
    if (product.has(number)) {
        double sale = product.sell(number);
        cashRegister.add(sale);
    } else {
        System.out.println("库存不足");
    }
}

private void viewCash() {
    System.out.println(cashRegister.toString());
}

import java.text.*;

public class CashRegister {
    private double cash;

    public CashRegister() {
    }

    public void add(double money) {
        cash += money;
    }

    @Override
    public String toString() {
        return "现金:$" + formatted(cash);
    }

    private String formatted(double amount) {
        return new DecimalFormat("###,##0.00").format(amount);
    }
}
英文:

I am having a weird issue where the function in my class keep returning NullPointerException, Here is my code below where I am referring to the cashRegister class and each time I use the functions (cashRegister.add() or cashRegister.toString()) it returns nullPointerException. Does anyone know how to fix?

private void sell() {
        Product product = product(readName());
        System.out.println("Selling " + product.getName());
        int number = readNumber();
        if (product.has(number)) {
            double sale = product.sell(number);
            cashRegister.add(sale);
        }
        else {
            System.out.println("Not enough stock");
        }
    }
private void viewCash() {
    System.out.println(cashRegister.toString());
} 

import java.text.*;

public class CashRegister {
    private double cash;

    public CashRegister() {
    }

    public void add(double money) {
        cash += money;
    }

    @Override
    public String toString() {
        return "Cash: $" + formatted(cash);
    }

    private String formatted(double amount) {
        return new DecimalFormat("###,##0.00").format(amount);
    }
}

答案1

得分: 0

你好,
你既没有实例化你的类,也没有将其实例传递给目标函数。

英文:

Good day,
You are neither instantiating your class nor passing its instance to the target function.

huangapple
  • 本文由 发表于 2020年9月2日 09:22:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/63697424.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定