【发布时间】:2016-10-15 07:05:27
【问题描述】:
所以我试图弄清楚如何让我的代码工作,但我不断收到 nullError。我没有正确存储我的数据吗?这是我的代码:
public class ProductTesterPart1{
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter the product number, name, stock, and price in that order.");
List<ProductPart1> products = new ArrayList<ProductPart1>();
String line = userInput.nextLine();
while (!line.equals("quit")) {
if (line == null || line.trim().isEmpty()) {
products.add(new ProductPart1());
}
else {
try {
Scanner s = new Scanner(line);
int number = s.nextInt();
String name = s.next();
int stock = s.nextInt();
double price = s.nextDouble();
products.add(new ProductPart1(number, name, stock, price));
}
catch (NoSuchElementException e) {
System.out.print("Error: " + e.getMessage());
}
}
}
for (ProductPart1 p : products) {
System.out.println(p.toString());
}
}
当然,那是驱动类,这是我的对象:
public class ProductPart1 {
//Declares variables
private int productNumber;
private String productName;
private int productStock;
private double productPrice;
//Constructor
public ProductPart1(){
setNumber(0);
productName = "Null";
productStock = 0;
productPrice = 0.0;
}
//Overload constructor
public ProductPart1(int number, String name, int stock, double price){
productNumber = number;
productName = name;
productStock = stock;
productPrice = price;
}
//set the number of the object
public void setNumber(int newNumber){
productNumber = newNumber;
}
//set the name of the object
public void setName(String newName){
productName = newName;
}
//set the stock of an object
public void setStock(int newStock){
productStock = newStock;
}
//set the price of an object
public void setPrice(double newPrice){
productPrice = newPrice;
}
//get the number of an object
public int getNumber(){
return getNumber();
}
//get the name of an object
public String getName(){
return productName;
}
//get the stock of an object
public int getStock(){
return productStock;
}
//get the price of an object
public double getPrice(){
return productPrice;
}
//toString to bring the object together.
public String toString(){
return new String("Number: " + getNumber() + " Name: " + productName + " Price: " + productPrice + " Stock: " + productStock);
}
【问题讨论】:
-
你能显示你的控制台日志吗?
-
这个不错
-
nullError:nullError:nullError:nullError:nullError:nullError:nullError:nullError:nullError:nullError:
-
此代码当前.. 错误/不清楚,无法重现该问题。首先,你不会得到“nullError”,而是来自
catch (NoSuchElementException e)的“Error: null”。所以打印堆栈跟踪以获得完整的异常。第二:getNumber()将导致无限循环。第三:如果第一个输入没有“退出”,则 main 方法中的while已经是一个无限循环。
标签: java arrays object storage tostring