H5W3
当前位置:H5W3 > 其他技术问题 > 正文

看一下下面的java代码,有什么问题?

包的结构

错误

Exception in thread "main" java.lang.NoClassDefFoundError: Product (wrong name: bluej/Product)

product.java

package bluej;
/**
 * Model some details of a product sold by a company.
 *
 * @author David J. Barnes and Michael Kolling
 * @version 2006.03.30
 */
public class Product {
    // An identifying number for this product.
    private int id;
    // The name of this product.
    private String name;
    // The quantity of this product in stock.
    private int quantity;

    /**
     * Constructor for objects of class Product.
     * The initial stock quantity is zero.
     * @param id The product's identifying number.
     * @param name The product's name.
     */
    public Product(int id, String name) {
        this.id = id;
        this.name = name;
        quantity = 0;
    }

    /**
     * @return The product's id.
     */
    public int getID() {
        return id;
    }

    /**
     * @return The product's name.
     */
    public String getName() {
        return name;
    }

    /**
     * @return The quantity in stock.
     */
    public int getQuantity() {
        return quantity;
    }

    /**
     * @return The id, name and quantity in stock.
     */
    public String toString() {

        return id + ": " +
               name +
               " stock level: " + quantity;
    }

    /**
     * Restock with the given amount of this product.
     * The current quantity is incremented by the given amount.
     * @param amount The number of new items added to the stock.
     *               This must be greater than zero.
     */
    public void increaseQuantity(int amount) {

        if(amount > 0) {
            quantity += amount;
        }
        else {
            System.out.println("Attempt to restock " +
                               name +
                               " with a non-positive amount: " +
                               amount);
        }
    }

    /**
     * Sell one of these products.
     * An error is reported if there appears to be no stock.
     */
    public void sellOne() {

        if(quantity > 0) {
            quantity--;
        }
        else {
            System.out.println("Attempt to sell an out of stock item: " + name);
        }
    }
}

StockDemo.java

package bluej;
import bluej.StockManager;
import bluej.Product;
/**
 * Demonstrate the StockManager and Product classes.
 * The demonstration becomes properly functional as
 * the StockManager class is completed.
 *
 * @author David J. Barnes and Michael Kolling
 * @version 2006.03.30
 */
public class StockDemo
{
    // The stock manager.
    private StockManager manager;

    /**
     * Create a StockManager and populate it with a few
     * sample products.
     */
    public StockDemo()
    {
        manager = new StockManager();
        manager.addProduct(new Product(132, "Clock Radio"));
        manager.addProduct(new Product(37,  "Mobile Phone"));
        manager.addProduct(new Product(23,  "Microwave Oven"));
    }

    /**
     * Provide a very simple demonstration of how a StockManager
     * might be used. Details of one product are shown, the
     * product is restocked, and then the details are shown again.
     */
    public void demo()
    {
        // Show details of all of the products.
        manager.printProductDetails();
        // Take delivery of 5 items of one of the products.
        manager.delivery(132, 5);
        manager.printProductDetails();
    }

    /**
     * Show details of the given product. If found,
     * its name and stock quantity will be shown.
     * @param id The ID of the product to look for.
     */
    public void showDetails(int id)
    {
        Product product = getProduct(id);
        if(product != null) {
            System.out.println(product.toString());
        }
    }

    /**
     * Sell one of the given item.
     * Show the before and after status of the product.
     * @param id The ID of the product being sold.
     */
    public void sellProduct(int id)
    {
        Product product = getProduct(id);

        if(product != null) {
            showDetails(id);
            product.sellOne();
            showDetails(id);
        }
    }

    /**
     * Get the product with the given id from the manager.
     * An error message is printed if there is no match.
     * @param id The ID of the product.
     * @return The Product, or null if no matching one is found.
     */
    public Product getProduct(int id)
    {
        Product product = manager.findProduct(id);
        if(product == null) {
            System.out.println("Product with ID: " + id +
                               " is not recognised.");
        }
        return product;
    }

    /**
     * @return The stock manager.
     */
    public StockManager getManager()
    {
        return manager;
    }

    public static void main(String[] args) {

      StockDemo w = new StockDemo();

        w.demo();

        w.showDetails(23);

        w.sellProduct(132);
    }
}

StockManage.java

package bluej;
import bluej.Product;
import java.util.ArrayList;

/**
 * Manage the stock in a business.
 * The stock is described by zero or more Products.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class StockManager
{
    // A list of the products.
    private ArrayList<Product> stock;

    /**
     * Initialise the stock manager.
     */
    public StockManager()
    {
        stock = new ArrayList<Product>();
    }

    /**
     * Add a product to the list.
     * @param item The item to be added.
     */
    public void addProduct(Product item)
    {
      for (int i = 0;i < stock.size();i++) {

        if (item.getID() == stock.get(i).getID()) {
          break;
        }

        while (i == stock.size() - 1) {

          stock.add(item);

        }
      }

    }

    /**
     * Receive a delivery of a particular product.
     * Increase the quantity of the product by the given amount.
     * @param id The ID of the product.
     * @param amount The amount to increase the quantity by.
     */
    public void delivery(int id, int amount)
    {
      Product pro = findProduct(id);

      pro.increaseQuantity(amount);
    }

    /**
     * Try to find a product in the stock with the given id.
     * @return The identified product, or null if there is none
     *         with a matching ID.
     */
    public Product findProduct(int id)
    {
      Product p = null;
      for (int i = 0;i < stock.size();i++) {

        if (stock.get(i).getID() == id) {
              p = stock.get(i);
              return p;
        }
      }
      return null;
    }

    /**
     * Locate a product with the given ID, and return how
     * many of this item are in stock. If the ID does not
     * match any product, return zero.
     * @param id The ID of the product.
     * @return The quantity of the given product in stock.
     */
    public int numberInStock(int id)
    {

      int number = 0;

      for (int i = 0;i < stock.size();i++) {
        if (stock.get(i).getID() == id) {
          number++;
        }
      }

      if (number == 0) {
          return 0;
      } else {
        return number;
      }
    }

    /**
     * Print details of all the products.
     */
    public void printProductDetails()
    {
      for (int i = 0;i < stock.size();i++) {

        System.out.println("Product:" + (i + 1) + "Information:" +stock.get(i).toString());
      }
    }

    /**
    * Find product by getting the name of product
    */
    public Product findProductByName(String name) {
      Product n = null;
      for (int i = 0;i < stock.size();i++) {

        if (name == stock.get(i).getName()) {
              n = stock.get(i);
              return n;
        }

        }
       return null;
      }

    public void printLowStockProducts(int lowsize)
    {
      for (int i = 0;i < stock.size();i++) {

          if(stock.get(i).getQuantity() < lowsize){

          System.out.println("Product:" + (i + 1) + "Information:" +stock.get(i).toString());
      }
      }
    }
}

main函数在StockDemo.java中,但无法运行!!!

错误如下:

Exception in thread "main" java.lang.NoClassDefFoundError: Product (wrong name: bluej/Product)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2625)
    at java.lang.Class.getMethod0(Class.java:2866)
    at java.lang.Class.getMethod(Class.java:1676)
    at sun.launcher.LauncherHelper.getMainMethod(LauncherHelper.java:494)
    at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:486)

回答:

我把你的代码copy了一份运行了一下,没有报找不到类的错,可能找不到类的问题多半确实如楼上所说,没有编译,但是我的代码编译后运行还是报错,报的空指针的

clipboard.png

简单看了一下你报错的地方,是查询完product,再去增加库存的时候,prod为null,所以报错

clipboard.png
为啥prod为null,是因为debug可以看到,你的manager类初始化后的prod集合为空,所以根据id找不到对应的prod

clipboard.png

有待改进问题一:
根据id去查询数据后,本身查询方法默认的初始值就是null了,所以在调用查询方法时,就本身应该考虑这个查询方法是可能返回null的,所以应该要再调用完查询方法后,首先检查一下是否为null,再做后续操作

clipboard.png

那为啥这个manager类里的prod集合大小为0呢?你前面也有增加prod的操作的

clipboard.png

其实问题就是出在这个manager增加prod的方法里,查看StockManager.addProduct

clipboard.png

可以看到,你的逻辑估计是想做图上所说的两个事,但是这样做,有些问题
有待改进问题二:
最开始的时候集合stock就是空的,所以第一次addprodcut的时候,这个for循环就走不进去,所以后续也走不进去,因为你的stock.add方法写在循环里了,所以stock集合一直为空
有待改进问题三:
list集合本身add方法默认就是添加到集合最后的,所以没有必要去判断循环的位置,只要前面检验id不同了,就可以直接调用
所以建议以下修改:

clipboard.png

修改后,程序看起来是正常了,起码没有报错,至于业务上(比如库存)是否有问题,你自己再多多斟酌一下

clipboard.png

回答:

请问你编译了吗

本文地址:H5W3 » 看一下下面的java代码,有什么问题?

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址