2013-02-22 2 views
0

이 루프 중에는 선택할 수있는 항목이 4 개 있습니다. 커피 (1), 라떼 (2), 카푸치노 (3), 에스프레소 (4). 시뮬레이션은 각 고객의 주문 및 수량을 채우기 위해 일련의 난수를 선택하고 각 고객의 총 비용을 계산합니다. 이제이 while 루프 이후에 판매 보고서를 작성해야하며 각 품목의 판매 총액을 계산해야합니다. 숫자가 무작위이고 고객의 수에 따라 루프가 반복되므로 어떻게해야합니까?루프 내 각 품목의 총 판매 비용은 어떻게 받습니까?

while (CustomersSimulated <= MaxCustomersSimulated) 
     { 
        //customer number 
     System.out.println("Customer " + CustomersSimulated);  


       //one random item for each customer  
    Random RandomList = new Random(); 
    int RandomItem = RandomList.nextInt(4) + 1; 

    if (RandomItem == 1) 
     { 
     System.out.println("Item purchased: Coffee"); 
     final double CoffeePrice = 1.50; 

          //random quantity for the item   
     Random RandomListTwo = new Random();  
     int RandomQuantity = RandomListTwo.nextInt(5) + 1; 
     System.out.println("Quantity purchased: " + RandomQuantity); 

          //total cost for the one customer  
     double TotalCoffeeCost = RandomQuantity * CoffeePrice; 
     System.out.println("Total Cost: $" + NumberFormat.format(TotalCoffeeCost)); 
     } 
    else if (RandomItem == 2) 
     { 
     System.out.println("Item purchased: Latte"); 
     final double LattePrice = 3.50; 

     Random RandomListTwo = new Random(); 
     int RandomQuantity = RandomListTwo.nextInt(5) + 1; 
     System.out.println("Quantity purchased: " + RandomQuantity); 

     double TotalLatteCost = RandomQuantity * LattePrice; 
     System.out.println("Total Cost: $" + NumberFormat.format(TotalLatteCost)); 
     } 
    else if (RandomItem == 3) 
     { 
     System.out.println("Item purchased: Cappuccino"); 
     final double CappuccinoPrice = 3.25; 

     Random RandomListTwo = new Random(); 
     int RandomQuantity = RandomListTwo.nextInt(5) + 1; 
     System.out.println("Quantity purchased: " + RandomQuantity); 

     double TotalCappuccinoCost = RandomQuantity * CappuccinoPrice; 
     System.out.println("Total Cost: $" + NumberFormat.format(TotalCappuccinoCost)); 
     } 
    else if (RandomItem == 4) 
     { 
     System.out.println("Item purchased: Espresso"); 
     final double EspressoPrice = 2.00; 

     Random RandomListTwo = new Random(); 
     int RandomQuantity = RandomListTwo.nextInt(5) + 1; 
     System.out.println("Quantity purchased: " + RandomQuantity); 

     double TotalEspressoCost = RandomQuantity * EspressoPrice; 
     System.out.println("Total Cost: $" + NumberFormat.format(TotalEspressoCost)); 
     } 

    System.out.println(" "); 

    CustomersSimulated++; 
    } 
+0

[시도한 내용] (http : //www.whathaveyoutried). (힌트 : 아마도 여러 개의 카운터가 필요할 것입니다.) –

+0

while 루프 내에서 for 문을 시도했지만 고객이 특정 횟수만큼 구매 한 횟수 대신 비용을 함께 추가하는 방법을 모르기 때문에 문제가 해결되지 않았습니다. 목. – Pandokie

+0

우리가 당신을 도울 수 있도록 코드를 게시하십시오. 예를 들어 고객이 5 라떼를 구입했다는 것을 알고 있다면 라떼 비용은 얼마입니까? 어떻게 계산 했니? –

답변

0

다음은 어떻게 대답할까요? @IswantoSan이 말한 것처럼 NumberFormat.format()은 컴파일되지 않으므로 변경했습니다. 또한 루프를 반복 할 때마다 발생하는 모든 재 초기화를 제거했습니다. 그것은 불필요합니다. 그 훨씬 더 많은 기억을 차지하지는 않지만 나는 그것이 항상 좋은 습관이라고 전했다. 또한 변수 이름의 첫 번째 문자는 소문자 여야합니다. 다시 말하지만, 나는 그것이 항상 좋은 습관이라고 들었다. 내가 틀렸을 수도있다.

이번이 검색 되었기를 바랍니다.

final static double espressoPrice = 2.00; 
final static double cappuccinoPrice = 3.25; 
final static double lattePrice = 3.50; 
final static double coffeePrice = 1.50; 

public static void main(String[] args) { 

    int customersSimulated = 0; 
    int maxCustomersSimulated = 4; 
    int randomQuantity = 0; 
    double total = 0; 

    double totalCoffee = 0; 
    double totalCappuccino = 0; 
    double totalLatte = 0; 
    double totalEspresso = 0; 

    DecimalFormat df = new DecimalFormat("##.##"); 

    while (customersSimulated <= maxCustomersSimulated) { 

     System.out.println("Customer " + customersSimulated);  

     Random randomList = new Random(); 
     int randomItem = randomList.nextInt(4) + 1; 

     if (randomItem == 1) { 

      System.out.println("Item purchased: Coffee"); 
      randomQuantity = randomList.nextInt(5) + 1; 
      System.out.println("Quantity purchased: " + randomQuantity); 
      double totalCoffeeCost = randomQuantity * coffeePrice; 
      System.out.println("Total Cost: $" + df.format(totalCoffeeCost)); 

      totalCoffee+=totalCoffeeCost; 
     } else if (randomItem == 2) { 

      System.out.println("Item purchased: Latte"); 
      randomQuantity = randomList.nextInt(5) + 1; 
      System.out.println("Quantity purchased: " + randomQuantity); 
      double totalLatteCost = randomQuantity * lattePrice; 
      System.out.println("Total Cost: $" + df.format(totalLatteCost)); 

      totalLatte+=totalLatteCost; 
     } else if (randomItem == 3) { 

      System.out.println("Item purchased: Cappuccino"); 
      randomQuantity = randomList.nextInt(5) + 1; 
      System.out.println("Quantity purchased: " + randomQuantity); 
      double totalCappuccinoCost = randomQuantity * cappuccinoPrice; 
      System.out.println("Total Cost: $" + df.format(totalCappuccinoCost)); 

      totalCappuccino+=totalCappuccinoCost; 
     } else if (randomItem == 4) { 

      System.out.println("Item purchased: Espresso"); 
      randomQuantity = randomList.nextInt(5) + 1; 
      System.out.println("Quantity purchased: " + randomQuantity); 
      double totalEspressoCost = randomQuantity * espressoPrice; 
      System.out.println("Total Cost: $" + df.format(totalEspressoCost)); 

      totalEspresso+=totalEspressoCost; 
     } 

     System.out.println(); 
     System.out.println("Total Coffee Cost: $" + totalCoffee); 
     System.out.println("Total Cappuccino Cost: $" + totalCappuccino); 
     System.out.println("Total Llatte Cost: $" + totalLatte); 
     System.out.println("Total Espresso Cost: $" + totalEspresso); 
     System.out.println(); 

     customersSimulated++; 
    } 
} 

기본적으로 당신이 초기화하고 루프 내에서, 그 동안 루프 외부로 +=를 변수를 정의 할 때, 그것은 루프 외부에서 액세스 할 수 있으며, 코드가 실행 된 것으로 걸쳐 "기억"될 것입니다; 그게 너에게 의미가 있다면.

+0

알겠습니다. 감사. 이것은 제가 맞으려고했던 누산기보다 훨씬 더 쉽게 보입니다. – Pandokie

0

당신은 그 경우-else 문 내부에 선택되어 값 언제든지 각 항목에 대한 전역 변수를 생성하고 증가 할 수있다. 그런 식으로 무작위로 선택 되더라도 전역 변수가 증가합니다. 나중에 가격에 따라 합계를 계산할 수 있습니다. 그게 네가 찾고 있었던 것이기를 바란다.

+0

변수는 "글로벌"(또는 더 정확하게는 멤버 또는 클래스 변수) 일 필요는 없지만 게시 된 OP와 동일한 방법으로 만 사용되는 경우 쉽게 로컬 변수가 될 수 있습니다. –

+0

당신은 절대적으로 옳습니다. 그 점을 지적 해 주셔서 감사합니다. DERP! – Bibodha

1

내가 생각할 수있는 유일한 방법은 네 가지 카운터를 만들고 매번 추가하여 각 판매를 저장하는 것입니다.

0

마찬가지로 다른 말로하면 루프 외부에 카운터 값을 새로 만들어 합계를 저장하십시오. 어쨌든 코드

 double TotalAllCoffeeCost = 0; 
     double TotalAllLatteCost = 0; 
     double TotalAllCappuccinoCost = 0; 
     double TotalAllEspressoCost = 0; 
     while (CustomersSimulated <= MaxCustomersSimulated) { 
      // customer number 
      System.out.println("Customer " + CustomersSimulated); 

      // one random item for each customer 
      Random RandomList = new Random(); 
      int RandomItem = RandomList.nextInt(4) + 1; 

      if (RandomItem == 1) { 
       System.out.println("Item purchased: Coffee"); 
       final double CoffeePrice = 1.50; 

       // random quantity for the item 
       Random RandomListTwo = new Random(); 
       int RandomQuantity = RandomListTwo.nextInt(5) + 1; 
       System.out.println("Quantity purchased: " + RandomQuantity); 

       // total cost for the one customer 
       double TotalCoffeeCost = RandomQuantity * CoffeePrice; 
       TotalAllCoffeeCost+=TotalCoffeeCost; 
       System.out.println("Total Cost: $" 
         + new DecimalFormat().format(TotalCoffeeCost)); 
      } else if (RandomItem == 2) { 
       System.out.println("Item purchased: Latte"); 
       final double LattePrice = 3.50; 

       Random RandomListTwo = new Random(); 
       int RandomQuantity = RandomListTwo.nextInt(5) + 1; 
       System.out.println("Quantity purchased: " + RandomQuantity); 

       double TotalLatteCost = RandomQuantity * LattePrice; 
       TotalAllLatteCost+=TotalLatteCost; 
       System.out.println("Total Cost: $" 
         + new DecimalFormat().format(TotalLatteCost)); 
      } else if (RandomItem == 3) { 
       System.out.println("Item purchased: Cappuccino"); 
       final double CappuccinoPrice = 3.25; 

       Random RandomListTwo = new Random(); 
       int RandomQuantity = RandomListTwo.nextInt(5) + 1; 
       System.out.println("Quantity purchased: " + RandomQuantity); 

       double TotalCappuccinoCost = RandomQuantity * CappuccinoPrice; 
       TotalAllCappuccinoCost+=TotalCappuccinoCost; 
       System.out.println("Total Cost: $" 
         + new DecimalFormat().format(TotalCappuccinoCost)); 
      } else if (RandomItem == 4) { 
       System.out.println("Item purchased: Espresso"); 
       final double EspressoPrice = 2.00; 

       Random RandomListTwo = new Random(); 
       int RandomQuantity = RandomListTwo.nextInt(5) + 1; 
       System.out.println("Quantity purchased: " + RandomQuantity); 

       double TotalEspressoCost = RandomQuantity * EspressoPrice; 
       TotalAllEspressoCost+=TotalEspressoCost; 
       System.out.println("Total Cost: $" 
         + new DecimalFormat().format(TotalEspressoCost)); 
      } 

      System.out.println(" "); 

      System.out.println("Total Cofee Cost : " + new DecimalFormat().format(TotalAllCoffeeCost)); 
      System.out.println("Total Latte Cost : " + new DecimalFormat().format(TotalAllLatteCost)); 
      System.out.println("Total Cappucino Cost : " + new DecimalFormat().format(TotalAllCappuccinoCost)); 
      System.out.println("Total Espresso Cost : " + new DecimalFormat().format(TotalAllEspressoCost)); 

      CustomersSimulated++; 
     } 

: format 정적 방법이 아니기 때문에

NumberFormat.format(...) 

컴파일하지 않습니다

이를 참조하십시오.

관련 문제