Создание промежуточного итога для одного из моих методов - PullRequest
0 голосов
/ 08 ноября 2018

Здравствуйте, у меня проблемы с созданием промежуточного итога одного из моих методов.

public double calcProduct()
{
   productTotal = price * qty * shipCost;
   return productTotal;
}

метод, который я перечислил выше, должен рассчитать общее количество созданных 4 экземпляров, но по какой-то причине онскладывает одинаковое количество «562», несмотря на стоимость доставки и стоимость всех продуктов по-разному.Мне также нужно общее количество 4 экземпляров в одной установленной цене.у меня также есть статический двойник под названием productTotal неинициализированный.Редактировать: вот копия моего кода для метода SalesOrder и основного метода:

Main:

public class SalesOrderDemo


  // and initialize it to 0
  double grandTotal = 0;

  // Print out a heading line as follows:
  //     "Sales Orders"
  System.out.println("Sales Orders");
  //     "------------"
  System.out.println ("------------");

  // Orders to place ... 
  System.out.println ("Orders to place...");
  //    Use the overloaded constructor to create 
  //    the Following instances of Sales Order:
  //
  // Instance #1 -- instance name: samsungTV
  //  "Samsung 65 inch Television" - qty 1 - price $199.99
  //      To be shipped normal
  SalesOrder Instance1 = new SalesOrder();
  Instance1.setProductName ("Samsung 65 inch Television");
  Instance1.setQty (1);
  Instance1.setPrice(1599.99);
  Instance1.calcShipping("normal");
  // Instance #2 -- instance name: smartLights
  //  "Hue Smart Lights" - qty 6 - price $49.95
  //      To be shipped same day
  SalesOrder Instance2 = new SalesOrder();
  Instance2.setProductName ("Hue Smart Lights");
  Instance2.setQty (6);
  Instance2.setPrice(49.95);
  Instance2.calcShipping("sameDay");
  // Instance #3 -- instance name: bathTowels
  //  "Bathrool Towels" - qty 8 - price $19.45
  //      To be shipped 2nd day
  SalesOrder Instance3 = new SalesOrder();
  Instance3.setProductName ("Bathroom Towels");
  Instance3.setPrice(19.45);
  Instance3.setQty(8);
  Instance3.calcShipping("2-day");

  // Instance #1 -- instance name: samsungTV
  //  "Dinner Plates" - qty 15 - price $2.50
  //      To be shipped same day
  SalesOrder Instance4 = new SalesOrder();
  Instance4.setProductName("Dinner Plates");
  Instance4.setQty(15);
  Instance4.setPrice(2.50);
  Instance4.calcShipping("sameDay");


  // Execute the mutator method "calcShipping" to add the 
  //    appropriate shipping fee to the cost of the product
  // The method will pass the shipping type string parameter:
  //    A character to store the type of shipping method
  //        "normal" for no additional shipping charge
  //        "2-day" for adding $2 to the shipping fee for 2 day delivery
  //        "same" for adding $10 to the shipping fee for same day delivery
  // Execute the method for each of the instances you created above



  // Execute the get method "calcProdcut" to 
  //    1. Calculate the total amount for each product,
  //    2. Print the products information on each line
  //    3. Return to total amount value to be accumulated into "grandTotal"
  // Execute the method for each of the instances you created above
  Instance1.calcProduct();
  Instance2.calcProduct();
  Instance3.calcProduct();
  Instance4.calcProduct();

  grandTotal = Instance1.calcProduct() + Instance2.calcProduct()
  + Instance3.calcProduct() + Instance4.calcProduct();
  // Print all total of all of the orders as shown on the example
  // Format to 2 decimal places
  //    Don't forget to print a blank line

  Instance1.printProduct();
  System.out.println("");
  Instance2.printProduct();
  System.out.println("");
  Instance3.printProduct();
  System.out.println("");
  Instance4.printProduct();
  System.out.println(" ");
  System.out.println("The total of the orders are: " + grandTotal);

}}

1 Ответ

0 голосов
/ 08 ноября 2018

Похоже, у вас возникло некоторое недопонимание того, что "методы экземпляра" позволяют вам делать.

Итак, вы вызываете calcProduct дважды, но никакой другой экземпляр SalesOrder не знает о значениях других, и это специально. Независимо от того, сколько раз вы запускаете этот метод, результат должен быть одинаковым.

Как говорится, это все, что вам нужно. Доставка, вероятно, не считается частью цены товара. И это должно быть добавлено, может быть, а не умножено (при условии, что все товары неограниченного количества отправляются сразу по фиксированной ставке)

public double calcProduct() {
    return price * qty;
}

Правильный способ подсчета суммы - это сложить каждое, как вы уже делаете. Методы получения не должны иметь побочных эффектов и изменять результаты других экземпляров.

Обратите внимание, было бы намного проще, если бы вы использовали цикл над массивом

List<SalesOrder> orders = new ArrayList<>();
// add orders 
double grandTotal = 0;
for (SalesOrder so : orders) grandTotal += (so calcProduct() + so.calcShipping());
...