Using enhanced for loop to print inputs from user and update variable

Viewed 33

Whenever the inputs for the my static variable total are entered by the user it will not update by adding the next input to it using +=, instead it seems to add the two together giving me double the amount. I thought of using a regular for loop under the enhanced for loop to iterate the static variable but I that did not work either.

    while(isRunning) {
      try {
        System.out.println("Please enter the name of your item you want to add: (type quit to exit) ");
          String item = input.nextLine();

        if(item.equalsIgnoreCase("quit")) {
          break;
        }
        System.out.println("Please enter the price of the item to be added to the invoice. ");
          receipt.setTotal(input.nextDouble());
          input.nextLine();
          itemList itemlist = new itemList(item, Invoice.total);
          price.add(itemlist);

      } catch (InputMismatchException e) {
        System.out.println("Exception caught!");
      }

      for(Invoice itemization : price) {
        Invoice.total += itemization.getTotal();
        System.out.println();
        System.out.println("Item: " + itemization.getItem() + "\nPrice: " + itemization.getTotal());
        System.out.println("Subtotal: " + Math.round(receipt.getTotal() * 100.00) / 100.00);

}



import java.util.*;

public class Invoice {

  static Double total;
  public String item;
  List<Invoice> price = new ArrayList<>();

  public String getItem() {
    return item;
  }

  public double getTotal() {
    return total;
  }

  public void setTotal(Double total) {
    Invoice.total = total;
  }

  public void endBalance() {

    if (getTotal() > 0.0) {
    System.out.println();
    System.out.println("$" + getTotal() + " Will be deposited once cleared. ");
    System.out.println();
    System.out.println("Expect most transfer to deposit to your account with 3 to 5 business days. ");
    System.out.println();

    } else {
      System.out.println("Available balance too low for bank deposit. ");
    }
  }

  // @Override
  // public String toString() {
  // //   return receipt.toString;
  // }
}

class itemList extends Invoice {

  public itemList(String item, Double total) {
    this.item = item;



  }

}
1 Answers

As Invoice's getTotal() method returns the value of the static variable, Invoice.total += itemization.getTotal(); is effectively a Invoice.total *= 2;. What did you expect?

Related