Java 面向对象程序中的空指针错误
我正在开发一个程序,该程序将用户的输入输入保存在一个单独的类中的数组中,然后将文件中的数据输入到同一个数组中。 我遇到的问题是代码可以编译,但在调用addStock以及addStock中的第一个while语句时,我在main中收到了一个空指针错误。 谢谢你的帮助 INVENTORY.JAVAJava 面向对象程序中的空指针错误,java,nullpointerexception,Java,Nullpointerexception,我正在开发一个程序,该程序将用户的输入输入保存在一个单独的类中的数组中,然后将文件中的数据输入到同一个数组中。 我遇到的问题是代码可以编译,但在调用addStock以及addStock中的第一个while语句时,我在main中收到了一个空指针错误。 谢谢你的帮助 INVENTORY.JAVA import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; /
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
//program skeleton is based on previous inventory.java(v 1.0) which was in turn based on divider.java(v 1.0)
//item data is now moved into a stock array using the stock.class,see stock.java notes for info on its implementation.
public class Inventory
{
private static int MAX_ITEMS = 100; //change based on total # of unique items
private Stock[] d_list; //creation of Stock array object
private int d_nextItem; //used to count total # of unique items
//constructor for inventory
public Inventory(){
d_list = new Stock[MAX_ITEMS];
d_nextItem = 0;
}
//user imputs item and info and is inputed into stock array d_list
//not used
public void addStock(String name, String identifier, int quantity,
double unitCost, double sellingPrice ){
Scanner keyboard = new Scanner(System.in);
name = null;
identifier = null;
quantity = 0;
unitCost = 0.0;
sellingPrice = 0.0;
String answer = null;
String cont = null;
while(!answer.equals("yes") && !answer.equals("no")){
System.out.println("do you want to input an additional item into the stock manually?(yes or no)");
answer = keyboard.next();
if(!answer.equals("yes") && !answer.equals("no")){
System.out.println("you must enter yes or no");
}
}
if(answer.equals("yes")){
while(cont.equals("yes")){ //having an error here
System.out.println("Enter the name of the item");
name = keyboard.next();
System.out.println("Enter the id tag");
identifier = keyboard.next();
System.out.println("Enter the quantity of "+name);
quantity = keyboard.nextInt();
System.out.println("Enter the Cost for the item");
unitCost = keyboard.nextDouble();
System.out.println("Enter the sales price of the item");
sellingPrice = keyboard.nextDouble();
System.out.println("do you want to enter info for a second item?");
while(!cont.equals("yes") && !cont.equals("no")){
cont = keyboard.next();
System.out.println("you must enter yes or no");
}
d_list[d_nextItem] = new Stock(name, identifier, quantity, unitCost, sellingPrice);
d_nextItem += 1;
}
}
return;
}
public void loadInventory(String fileName)
throws FileNotFoundException{
if ( (fileName != null) && (!fileName.equals("")) ){
Scanner ldInv = new Scanner(new File(fileName));
String newLine = null;
//initialization for variables
String name = null;
String identifier = null;
int quantity = 0;
double unitCost = 0.0;
double sellingPrice = 0.0;
//reading of file into the Stock array
while (ldInv.hasNextLine() && d_nextItem < MAX_ITEMS){
if (ldInv.hasNextDouble()){
System.err.println("Error:NO name of product detected!");
System.exit(2);
} else {
name = ldInv.next();
}
if (ldInv.hasNextDouble()){
System.err.println("Error:NO product identifier detected!");
System.exit(2);
} else {
identifier = ldInv.next();
}
if (ldInv.hasNextInt()){
quantity = ldInv.nextInt();
} else {
System.err.println("Error: Quantity of item is missing!");
System.exit(2);
}
if (ldInv.hasNextDouble()){
unitCost = ldInv.nextDouble();
} else {
System.err.println("Error: Price of Item is missing!");
System.exit(2);
}
if (ldInv.hasNextDouble()){
sellingPrice = ldInv.nextDouble();
} else {
System.err.println("Error: Sales price of Item is missing!");
System.exit(2);
}
d_list[d_nextItem] = new Stock(name, identifier, quantity, unitCost, sellingPrice);
newLine = ldInv.nextLine();
d_nextItem += 1;
}
}
if (d_nextItem == 0){
System.err.println("There is no data in this file");
System.exit(2);
}
return;
}
//prints onto screen data taken from file in a format to align with headings
public void printInventory(){
System.out.println();
System.out.println(d_list[0]);
for (int i = 0; i < d_nextItem; i++){
Stock stock = d_list[i];
System.out.format("%-20s\t%9s\t%1d\t%9.2f\t%9.2f\t%9.2f\t%9.2f\n",
stock.getName(),
stock.getIdentifier(), stock.getQuantity(), stock.getUnitCost(),
stock.getSellingPrice(), stock.getTotalCost(), stock.getTotalSellingPrice());
/*
System.out.println(stock.getName() + "\t" + stock.getIdentifier() + "\t" +
stock.getQuantity() + "\t" + stock.getUnitCost() + "\t" +
stock.getSellingPrice() + "\t" + stock.getTotalCost() +
"\t" + stock.getTotalSellingPrice());
*/
}
return;
}
//calculates total value of all items from the file
public double getTotalSalesPrice(){
double totalSP = 0.0;
for (int i = 0; i < d_nextItem; i++){
Stock stock = d_list[i];
totalSP += stock.getTotalSellingPrice();
}
return totalSP;
}
//calculates total cost of all items from the file
public double getTotalCost(){
double totalV = 0.0;
for (int i = 0; i < d_nextItem; i++){
Stock stock = d_list[i];
totalV += stock.getTotalCost();
}
return totalV;
}
/*
//user inputs name returns info from stock
//not used
public Stock getStock(String name){
}
*/
public static void main(String[] args) throws FileNotFoundException{
String name = null;
String identifier = null;
int quantity = 0;
double unitCost = 0.0;
double sellingPrice = 0.0;
if (args.length!=1){
System.err.println("Usage:java Inventory <input file name>");
System.exit(1);
}
Inventory inventory = new Inventory();
inventory.addStock(name, identifier, quantity, unitCost, sellingPrice);
inventory.loadInventory(args[0]);
inventory.printInventory();
System.out.format("\nTotal potential sales from inventory = %6.3f\n",
inventory.getTotalSalesPrice());
System.out.format("\nTotal store cost of inventory = %6.3f\n",
inventory.getTotalCost());
}
}
您正在将
answer
设置为null
,然后将其与一些String
值进行比较。那没有道理。在将变量answer
与任何对象进行比较之前,您可能希望从System.in
中读取一些输入。将answer
设置为null
,然后调用
answer.equals("yes")
由于answer
为空,因此引发空指针异常
您应该将其设置为非null的值,例如空字符串,或者如其他人所指出的,在比较之前请求输入,以便它肯定是非null的,或者使用Yoda样式的equals检查
"yes".equals(answer)
让我们从您的代码块开始
String answer = null;
String cont = null;
while(!answer.equals("yes") && !answer.equals("no")){
第1行:您将答案设置为空
第3行:查询答案,看看它是否等于某个值
现在,请注意javaNull
是一种类型,就像String
一样<但是,code>Null是任何其他类型的子集。这意味着当你问
answer.equals()
您实际上是在对java说,新字符串(答案).equals()
。
因为答案实际上是null
类型,所以java将您的代码解释为newnull().equals()
问题是,类型
null
没有方法。因此,它抛出一个NullPointerException
,因为您永远不能对任何null
类型的对象调用方法。您正在显式设置String answer=null
,然后立即尝试在while循环中调用该对象上的方法(在该循环中,answer.equals…
)
考虑到程序这一部分的逻辑,您应该可以安全地使用do…while
循环。像这样:
do{
// get user input, set answer variable
while(answer.equals("yes") && !answer.equals("no"));
使用while循环时,不要将
answer
声明为null,请先尝试读取输入,或使用类似(“”)
之类的无效内容对其进行初始化,该内容无法识别,但已初始化字符串answer您正在显式设置字符串answer=null代码>。为什么要填充它?作为一个侧节点,我不明白为什么要传递名称
,标识符
,数量
,单位成本
和销售价格
作为addStock()
的参数,只是为了在函数开始时重置它们。
do{
// get user input, set answer variable
while(answer.equals("yes") && !answer.equals("no"));