英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论