大家好我刚刚开始编程,我对Java完全不满意。基本上我在控制台窗口中输入一个值后,使用startScan()方法使用BlueJ得到java.lang.NullPointerException错误:
import java.util.*;
public class Machine
{
private double balance;
private int count;
private ItemTable Database;
ArrayList<ItemType> items = new ArrayList<>();
ArrayList<ItemType> receipt = new ArrayList<>();
public Machine()
{
balance = 0;
count = 0;
}
public void console()
{
startScan();
}
public void startScan()
{
System.out.println("Enter 'y' to begin, or 's' to shutdown.");
Scanner input = new Scanner(System.in);
boolean shutdown = false;
while (!shutdown)
{
String line = input.nextLine();
if (line.equals("s")){
shutdown = true;
System.exit(0);
}
else if (line.equals("y")){
System.out.println("Enter barcode or press 's' to checkout.");
scanItem();
}
}
}
public void scanItem()
{
Scanner input = new Scanner(System.in);
String line = input.nextLine();
if(Database.barcodeValidate(line))
{
balance += Database.getPrice(line);
count += 1;
receipt.add(new ItemType ("line", Database.getName(line), Database.getPrice(line)));
scanItem();
}
else if(line.equals("s"))
{
finishScan();
}
else
{
System.out.println("Invalid barcode.");
scanItem();
}
}
public void finishScan()
{
for(ItemType i : receipt) {
System.out.println(i.getName() + ", $"+i.getPrice());
}
System.out.println("For "+count+" items scanned, Total price: $"+balance +".");
}
}
来自另一个班级:
import java.util.ArrayList;
public class ItemTable
{
ArrayList<ItemType> items = new ArrayList<>();
public ItemTable()
{
items.add(new ItemType("0", "Orange", 3.50));
items.add(new ItemType("1", "Apple", 2));
items.add(new ItemType("2", "Lemon", 1.50));
items.add(new ItemType("3", "Garbage", 7.50));
items.add(new ItemType("4", "Grass", 20.00));
items.add(new ItemType("5", "Coke", 200));
items.add(new ItemType("6", "Lexus ISF", 120000));
items.add(new ItemType("7", "Lexus is250", 65000));
items.add(new ItemType("8", "Lexus is350", 72000));
items.add(new ItemType("9", "Lexus RC350", 78000));
}
public String getName(String Barcode)
{
for(ItemType i : items) {
if(Barcode.equals(i.getBarcode())) {
return i.getName();
}
}
return("Invalid barcode");
}
public double getPrice(String Barcode)
{
for(ItemType i : items) {
if(Barcode.equals(i.getBarcode())) {
return i.getPrice();
}
}
return (-1);
}
public boolean barcodeValidate(String Barcode)
{
if(Barcode.equals("0") || Barcode.equals("1") || Barcode.equals("2") || Barcode.equals("3") || Barcode.equals("4") || Barcode.equals("5") || Barcode.equals("6") || Barcode.equals("7") || Barcode.equals("8") || Barcode.equals("9")) {
return true;
}
else {
return false;
}
}
}
我正在努力使条形码有效(字符串0-9),该项目将被扫描到机器中,但不断收到nullpointer错误。
答案 0 :(得分:0)
您的变量“数据库”无法初始化(至少在您向我们展示的代码中没有)。 你需要有一个行
Database = new ItemTable();
除此之外:
"0".equals(barcode)
)。这样做的好处是,如果barcode
为空,则不会出现NullPointerException。