简体   繁体   English

使用增强的 for 循环打印来自用户的输入并更新变量

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

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.每当用户输入我的 static 变量总计的输入时,它不会通过使用 += 将下一个输入添加到它来更新,而是似乎将两者加在一起给了我两倍的数量。 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.我想在增强的 for 循环下使用常规 for 循环来迭代 static 变量,但我也没有工作。

    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;



  }

}

As Invoice 's getTotal() method returns the value of the static variable, Invoice.total += itemization.getTotal();由于InvoicegetTotal()方法返回 static 变量的值,因此Invoice.total += itemization.getTotal(); is effectively a Invoice.total *= 2;实际上是Invoice.total *= 2; . . What did you expect?你期待什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM