购物车二进制搜索

时间:2014-04-09 23:35:12

标签: java binary-search

该程序应该模仿杂货店的购物。它几乎完成,但我需要实现二进制搜索。它应该在数组购物车中搜索该人正在寻找的字符串。但是,它不起作用,我不知道如何解决它。如果你能弄清楚我需要如何修复它,我将不胜感激。我知道问题不在Item中。我得到的错误是ShoppingCart无法解析为变量

    // **********************************************************************
    //   ShoppingCart.java
    //
    //   Represents a shopping cart as an array of items
    // **********************************************************************

    import java.util.*;
    import java.text.NumberFormat;

    public class ShoppingCart
    {
     Scanner scan = new Scanner(System.in);

private int itemCount;      // total number of items in the cart
private double totalPrice;  // total price of items in the cart
private int capacity;       // current cart capacity
Item[] cart;
int i = 0; 

// -----------------------------------------------------------
//  Creates an empty shopping cart with a capacity of 5 items.
// -----------------------------------------------------------
public ShoppingCart()
{
  capacity = 5;
  itemCount = 0;
  totalPrice = 0.0;
  cart = new Item[capacity];
}

// -------------------------------------------------------
//  Adds an item to the shopping cart.
// -------------------------------------------------------
public void addToCart(String itemName, double price, int quantity)
{
  if(i == cart.length)
  {
    increaseSize();
  }
  else
  {
  Item newItem = new Item(itemName, price, quantity);
  cart[i] = newItem;
  totalPrice = (price*quantity)+totalPrice;
  itemCount++;
  i++;
  }
}

// -------------------------------------------------------
//  Returns the contents of the cart together with
//  summary information.
// -------------------------------------------------------
public String toString()
{
 NumberFormat fmt = NumberFormat.getCurrencyInstance();

 String contents = "\nShopping Cart\n";
 contents += "\nItem:\t\tUnit Price: \tQuantity:\t\tTotal:\n";

 for(int i = 0; i < itemCount; i++)
 contents += cart[i].toString() + "\n";

 contents += "\nTotal Price: " + fmt.format(totalPrice);
 contents += "\n";

 return contents;
}

// ---------------------------------------------------------
//  Increases the capacity of the shopping cart by 3
// ---------------------------------------------------------
private void increaseSize()
{
  Item[] temp = new Item[cart.length+3];
  for(int item=0; item < cart.length; item++)
  {
    temp[item] = cart[item];
  }
  cart = temp;
}

public void binarySearch(ShoppingCart sc)
{
  System.out.println("Type in the object you would like to search for: ");
  String object = scan.next();
  int high = cart.length-1;
  int low = 0;
  int middle = (low+high)/2;

  while(!(cart[middle].getName().equals(object)) && low<=high)
  {
    if((cart[middle].getName()).compareTo(object) > 0)
      if(cart[middle].getName().equals(object))
      high = middle-1;

      else
        low = middle+1;

      middle = (low+high)/2;
  }
    if(cart[middle].getName().equals(object))
      System.out.println("Your item is found!");
    else
      System.out.println("Your item is not found.");


  }     
}

import java.util.*;

public class Shop
{

    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        String userAns,name;
        int amount;
        double price;
        ShoppingCart newCart = new ShoppingCart();

        System.out.println("Would you like to shop at the store?");
        userAns = scan.nextLine();

        if(userAns.equalsIgnoreCase("yes"))
        {
            while(userAns.equalsIgnoreCase("yes"))
            {
                System.out.println("What are the item names?");
                name = scan.next();
                System.out.println("How many would you like to buy?");
                amount = scan.nextInt();
                System.out.println("How much is it?");
                price = scan.nextDouble();

                newCart.addToCart(name,price,amount);

                System.out.println(newCart);

                System.out.println("Would you like to continue shopping at the store?");
                userAns = scan.next();
            }

            System.out.println("Would you like to check your cart for an item?");
            String userScan = scan.next();

            if(userScan.equalsIgnoreCase("yes"))
                binarySearch(newCart);

        }
        else
            System.out.println("Have a nice day!");

    }
}
// ***************************************************************
//   Item.java
//
//   Represents an item in a shopping cart.
// ***************************************************************

import java.text.NumberFormat;

public class Item
{
private String name;
private double price;
private int quantity;


// -------------------------------------------------------
//  Create a new item with the given attributes.
// -------------------------------------------------------
public Item (String itemName, double itemPrice, int numPurchased)
{
 name = itemName;
 price = itemPrice;
 quantity = numPurchased;
}


// -------------------------------------------------------
//   Return a string with the information about the item
// -------------------------------------------------------
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();

return (name + "\t\t" + fmt.format(price) + "\t\t" + quantity + "\t\t"
+ fmt.format(price*quantity));
}

// -------------------------------------------------
//   Returns the unit price of the item
// -------------------------------------------------
public double getPrice()
{
 return price;
}

// -------------------------------------------------
//   Returns the name of the item
// -------------------------------------------------
public String getName()
{
 return name;
}

// -------------------------------------------------
//   Returns the quantity of the item
// -------------------------------------------------
public int getQuantity()
{
 return quantity;
}

}  

1 个答案:

答案 0 :(得分:0)

当您调用binarySearch(...)方法时,您将类名,ShoppingCart传递给方法参数,这对我或编译器没有意义。相反,你应该传递ShoppingCart变量newCart,这更有意义。

更改

binarySearch(ShoppingCart); // you're passing in a class here, not the object

为:

binarySearch(newCart); // here you pass in the ShoppingCart object declared earlier

修改
您的binarySearch方法被误解了。它是ShoppingCart类的一种方法,因此不应该将ShoppingCart对象传递给它,而应该在ShoppingCart对象上调用 。相反,你应该传入要搜索的对象。

总而言之:

  • 将binarySearch参数从ShoppingCart更改为Item。
  • 从该方法中获取所有用户输入输出。 I / O应该在main方法或单独的I / O类中。
  • 在ShoppingCart对象上调用方法,此处为newCart.binarySearch(someItem);