2013-12-11 2 views
0

내 CS 클래스 용 자동 판매기의 동작을 모방 한 프로그램을 작성하려고합니다. 나는 특정 슬롯에있는 아이템의 수를 나타내는 더블 어레이 스톡을 가지고있다. [나의 자동 판매기는 이상하고 다른 아이템의 1 컬럼을 가진 하나의 긴 자동 판매기와 비슷하다.] 여기 내 지금까지 코드 :왜 내 코드가 잘못된 결과를 내고 있습니까?

public class VendingMachine 
{ 
    // define fields here 
    public static double itemPrice[]; 
    public static String[] itemName; 
    public static int stock[][]; 
    public static int maxPerSlot; 
    public static double cashAmmount; 

    public VendingMachine(int numslots, int maxperslot, double cash) 
    { 
     final int numSlots = numslots; 
     maxPerSlot = maxperslot; 
     cashAmmount = cash; 
     stock = new int[numSlots][1]; 

     itemPrice = new double[numSlots]; 
     itemName = new String[numSlots]; 

     // complete this method 
    } 

    public void setProduct(int slot, String product, double price) 
    { int Slot = slot; 
     itemPrice[Slot] = price; 
     itemName[Slot] = product; 
     stock[Slot][0] = 0; 

     // 
    } 

    public void restockProduct(String product, int quantity) 
    { 
     String Product = product; 
     int Quantity = quantity; 

     for(int i = 0; i < itemName.length;i++){ 
      if (Quantity > (maxPerSlot-stock[i][0])){ 
      return; 
      } 
      if (Product.equals(itemName[i])&&Quantity < maxPerSlot){ 
        stock[i][0] += Quantity; 


      }else if ((maxPerSlot-stock[i][0])==0){ 

       continue; 

      } 
     } 

     //Put # of products in slot that holds it and if that slot is full put the rest in the next 
     //available slot that holds that product, if all full return error. 
    } 

    public double getCashOnHand() 
    { 
     return cashAmmount; // replace this line with your code 
    } 

    public int getQuantity(int slot) 
    { 
     return stock[slot][0]; // replace this line with your code 
    } 

    public int getQuantity(String product) 
    { int total = 0; 

     for (int i = 0; i<itemName.length;i++){ 
      if (product == itemName[i]){ 
       total += this.getQuantity(i); 
      } 
     } 
     return total; 
    } 

    public boolean buyItem(int slot) 
    { int snum = slot; 
     double price = 0; 
     if (stock[snum][0] != 0){ 
      stock[snum][0]--; 
     price= itemPrice[snum]; 
     cashAmmount += price; 
     return true; 
     } else { 
     return false;} 
     // replace this line with your code 
    } 
} 

하고 실행하는 주요 방법은 : 내 밖으로 때 넣어

true 
5.75 
8 
15 

:

public class vmd 
{ 
    public static void main(String[] args) 
    { 
     boolean success; 

     // vending machine w/ 20 slots, 10 items maximum per slot, $5 cash on hand 
     VendingMachine v = new VendingMachine(20, 10, 5.00); 
     v.setProduct(0, "Cheesy Poofs", 0.75); 
     v.setProduct(1, "Red Bull", 1.25); 
     v.setProduct(2, "Cheesy Poofs", 0.75); 
     v.restockProduct("Cheesy Poofs", 8); 
     v.restockProduct("Red Bull", 7); 
     v.restockProduct("Cheesy Poofs", 5); // 2 more go into slot 0, remaining 3 into slot 2 

     success = v.buyItem(0); 
     System.out.println(success); // should print "true" 

     System.out.println(v.getCashOnHand()); // should print "5.75" 

     System.out.println(v.getQuantity(2));// should print "9"  
     System.out.println(v.getQuantity("Cheesy Poofs")); // should print "12" 
    } 
} 

나는 이것이 내가 지속적으로 얻을 생각을 실행

나는 다음과 같이 생각합니다 :

true 
5.75 
9 
12 

을 출력합니다. 왜 이런거야? 나는 그것이 restockProduct() 메소드와 관련이 있다고 가정하고 있지만 그것을 좁히지 못하고 내 신경이 쓰이는 것처럼 보일 수 없다. 내 CS 교사에 따르면 restockProduct() 메소드는 지정된 제품의 주어진 수량을 자동 판매기에 추가하고 특정 종류의 제품을 보유하도록 지정된 첫 번째 슬롯에 가능한 많은 항목을 넣는 것으로 가정합니다 setProduct() 사용).

모든 항목이 첫 번째 슬롯에 맞지 않는 경우 해당 종류의 제품 등을 보유하는 두 번째 슬롯에 가능한 한 많은 나머지를 넣으십시오. 부분 크레딧의 경우, 귀하의 방법은 적어도 "지정된 제품에 대한 첫 번째 슬롯을 찾아 거기에 모든 항목을 넣어

+1

당신의 재입고 방법이하는 일은 그것이 무엇을해야하는지에 대한 설명에 닮지 않습니다. 스크랩하고 다시 시작하라고 제안하십시오. – Dmitri

+1

왜 9를 인쇄해야합니까? 슬롯 2에는 3 개의 항목이 있어야합니다. –

답변

1

을 자네 말이 맞아, restockProducts은 당신이 원하는 일을하지 않습니다 여기에 당신이 무엇을 :.. 그래서

public void restockProduct(String product, int quantity) 
{ 
    String Product = product; 
    int Quantity = quantity; 

    for(int i = 0; i < itemName.length;i++){ 
     if (Quantity > (maxPerSlot-stock[i][0])){ 
     return; 
     } 
     if (Product.equals(itemName[i])&&Quantity < maxPerSlot){ 
       stock[i][0] += Quantity; 


     }else if ((maxPerSlot-stock[i][0])==0){ 

      continue; 

     } 
    } 

보충하면 "Cheesy Poofs" 처음으로 다음과 같이 진행됩니다.

  1. 루프 0에서, 당신은 치즈 냄새 맡아서 8 아이템을 넣습니다.
  2. 루프 1에서 잘못된 유형이 있으므로 아무 것도 이동하지 않습니다.
  3. 루프 2에서 Cheesy Poofs가 있으므로 거기에 8을 넣습니다.

어떻게 든 첫 번째 슬롯에 8을 넣었다는 것을 기억해야합니다. 또한, 하나의 슬롯에 여러 슬롯을 넣을 수있는 메커니즘이 필요하고, 다른 슬롯에 몇 가지 슬롯을 넣을 수있는 메커니즘이 필요합니다. 지금은 코드에서 가능하지 않습니다.

0

귀하의 문제는 여기에 있습니다 :

for(int i = 0; i < itemName.length;i++){ 
    if (Quantity > (maxPerSlot-stock[i][0])){ 
     return; 
} 

첫 번째 호출이

v.restockProduct("Cheesy Poofs", 8); 

이 기계에 8 개 항목을두고 "구역질 나는 Poofs을"재고 보충 할 수 있습니다.

두 번째 전화

는 치즈 poofs을 재고 보충하기 :

v.restockProduct("Cheesy Poofs", 5); 

는 아무것도 할 수 없다. if 문에 수량 (5)이 maxPerSlot - current stock보다 크거나 (10-8) 또는 2이면 반환됩니다.

5가 2보다 크므로이 방법이 끝나고 컴퓨터에 아무 것도 추가되지 않습니다.

또한 8 개의 항목을 모두 컴퓨터에 추가하면 루프에서 벗어나는 일종의 컨트롤을 추가해야합니다. 그대로 두 개의 다른 슬롯에 8 개의 멍청이를 추가하고 있습니다. 첫 번째 Cheesy Poof 행에 8을 추가하면 남은 것에서 8을 제거해야합니다.

는 그 방법을 재구성의 자유를했다 이것은 당신이 달성하기 위해 노력하고 생각하는 것입니다 :

public void restockProduct(String product, int quantity) 
{ 
    String Product = product; 
    int Quantity = quantity; 

    for(int i = 0; i < itemName.length;i++){ 

     if (Product.equals(itemName[i])){ 

      if (Quantity > (maxPerSlot-stock[i][0])){ 
       Quantity -= maxPerSlot-stock[i][0]; 
       stock[i][0] += maxPerSlot-stock[i][0]; 

      } 
      if (Quantity <= (maxPerSlot-stock[i][0])){ 
       stock[i][0] += Quantity; 
       return; 
      } 
     } 
    } 
} 
0

당신이 다른 사람에 의해 설명 당신의 restockProduct 몇 가지 문제가있다, 어쨌든 당신은 당신에게 restockProduct 기능을 변경할 수 있습니다

public void restockProduct(final String product, int quantity) 
{ 
    for (int i = 0; i < itemName.length; i++) 
    { 
     if ((product.equals(itemName[i]) || "".equals(product)) && (maxPerSlot - stock[i][0]) > 0) 
     { 
      stock[i][0] += quantity; 
      if (stock[i][0] > maxPerSlot) 
      { 
       quantity = stock[i][0] - maxPerSlot; 
       stock[i][0] = maxPerSlot; 
      } 
      else 
       return; 
     } 
    } 

    if (quantity > 0) 
     throw new IllegalArgumentException("Cannot stock product"); 
} 

참고 :이 일에 우리가 확인하고 삽입 후 우리가 furthe 삽입해야 어떤 나머지가 없다 : 우리는 두 제품이 이미 또는 모든 비고 2에서 제품이 어디 어디에 슬롯에 제품을 삽입하고 r 또는 모든 것이 여기에있다

관련 문제