二进制搜索方法

时间:2014-02-15 21:08:24

标签: java search binary

嗨,这个程序就好像你在杂货店购物一样。唯一的问题是我无法完成二进制搜索。假设在数组购物车中搜索该人正在寻找的字符串。然而,它不太有效(意思是我不确定什么是错的)。如果你可以看看是否有明显的问题,那就太好了。谢谢你的帮助!

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 Sam's Club?");
        userAns = scan.nextLine();

        if(userAns.equalsIgnoreCase("yes"))
        {
            while(userAns.equalsIgnoreCase("yes"))
            {
                System.out.println("Please type in the products name you would like to purchase:");
                name = scan.next();
                System.out.println("Please type in the number of products you would like to purchase");
                amount = scan.nextInt();
                System.out.println("Please type in the amount of money it costs:");
                price = scan.nextDouble();

                newCart.addToCart(name,price,amount);

                System.out.println(newCart);

                System.out.println("Would you like to continue shopping at Sam's Club?");
                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!");

    }
}

    // **********************************************************************
    //   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()
{
  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.");


  }     
}

我认为这不是问题,但我会在下一个添加这个问题:

// ***************************************************************
//   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;
}

}  

0 个答案:

没有答案
相关问题