简体   繁体   English

我的程序只打印ArrayList的最后一个输入

[英]My program is printing only the last input from the ArrayList

I have another small class containing the main method that display the 我还有另一个小类,其中包含显示
invoice, but the toString method here is only displaying the last item entered, not the three itemnames,quantities, prices and totalPrice. 发票,但此处的toString方法仅显示最后输入的项目,而不显示三个项目名称,数量,价格和totalPrice。 I have doubts about addItemLine and toString . 我对addItemLine和toString有疑问。 Can someone see what I am missing here? 有人可以看到我在这里想念的吗? I was enable to past the lineItem class code. 我能够过去lineItem类代码。

import java.util.ArrayList;
import java.util.Scanner;


public class Transaction {
     private ArrayList<lineItem> lineItems;
     private int customerID;
     private String customerName; 


public Transaction (int customerID, String customerName){
      this.customerID= customerID;
      this.customerName= customerName;
      this.lineItems= new ArrayList<>();
}
    public int getcustomerID(){
        return customerID;
}
    public void setcustomerID(int customerID){
        this.customerID = customerID;
}

    public String getcustomerName(){
        return customerName;
}
    public void setcustomerName(String customerName){
        this.customerName = customerName;
}
    public ArrayList addItemLine(lineItem line){

          Scanner mykey=new Scanner(System.in);
          for (int i=0; i<2;i++){
          String k= line.getItemName();
          int m= line.getQuantity();
          double d= line.getPrice();   

          System.out.println("enter item name:");
          k = mykey.next();
          line.setItemName(k);
          System.out.println("enter quantity:");
          m= mykey.nextInt();
          line.setQuantity(m);
          System.out.println("enter unit price:");
          d= mykey.nextDouble();
          line.setPrice(d);
          line.getItemName(); line.getQuantity(); line.getPrice();
          lineItems.add(new lineItem(k,m,d));
    }
          return this.lineItems;
   }
       public void updateItem(String item, int quant, double pri){
           lineItem l= new lineItem(item, quant, pri);
           int m=0;
           m= l.getQuantity();
           m=m+quant;
           double tot=0;    
   }
   public double getTotalPrice(){
         double totalPrice = 0;

         for (int i =0;i<2; i++){
              lineItem item = lineItems.get(i);
              totalPrice = totalPrice + item.getTotalPrice();
          }
             return totalPrice;

}
public String getLineItem( String s, int d, double k){
      lineItem o= new lineItem(s,d,k);
      for (int i =0;i<2; i++){
      if (!s.equals(o.getItemName()))
      System.out.println("item not found");
      else
         s= (o.getItemName() + o.getQuantity() + o.getPrice());
}
     return s;
}
public String toString(lineItem lin) {
      String a="", b="";

      a=("Customer ID:" + this.getcustomerID() + "\n" + "Customer Name: " +   
      this.getcustomerName());
      for (int i=0; i<2;i++){
      b= ("\n\n" + lin.getItemName() + "\t" + "Qty" + lin.getQuantity() + "   
      "   
      + "@" + lin.getPrice() + "  "+ "\t" + "$" + lin.getTotalPrice());  
  }
      return a + b;
}

TransactionTesting: 交易测试:

    import java.util.Scanner;


   public class TransactionTesting {


          public static void main(String args[]) {
                String m=""; int g=0; double r=0; int id=0; String name="";

                Scanner mykey= new Scanner(System.in);
                System.out.println("enter customer name:");
                name= mykey.nextLine();
                System.out.println("enter customer ID:");


        id=mykey.nextInt();
            Transaction mytrans= new Transaction(id, name);
            lineItem line= new lineItem(m,g,r);
            mytrans.addItemLine(line);

            System.out.println(mytrans.toString(line));
         }
       }

Change your toString() method like this: 像这样更改您的toString()方法:

public String toString() {
        String a="", b="";

        a=("Customer ID:" + this.getcustomerID() + "\n" + "Customer Name: " +   
                this.getcustomerName());
        for (lineItem item : this.lineItems)
            b += ("\n\n" + item.getItemName() + "\t" + "Qty" + item.getQuantity() + "   "   
                    + "@" + item.getPrice() + "  "+ "\t" + "$" + item.getPrice());  

        return a + b;
    }

and from your test class call this method as the following: 并从您的测试类中调用此方法,如下所示:

System.out.println(mytrans.toString());

You don't need any argument in order to print your entire list. 您不需要任何参数即可打印整个列表。 Try to refactor your code a bit. 尝试重构一下代码。 It works, but it can be written better and better ;) 它可以工作,但是可以写得越来越好;)

1) The call 1)通话

System.out.println(mytrans.toString(line));

is printing out the single lineitem that is passed to it. 正在打印传递给它的单个lineitem。 What you probably intended was for Transaction.toString() to iterate over its list Transaction.lineItems and print each item in turn. 您可能想要的是让Transaction.toString()遍历其列表Transaction.lineItems并依次打印每个项目。

In fact Transaction.toString() doesn't need to take in a lineItem argument, the method should merely print out the internals of the class instance. 实际上, Transaction.toString()不需要接受lineItem参数,该方法仅应打印出类实例的内部。

2) There is a similar confusion in Transacton.addItemLine() . 2) Transacton.addItemLine()也有类似的混淆。 It accepts a lineItem, prompts the user for new values, updates lineItem.. then constructs a new lineItem to store in Transaction.lineItems . 它接受一个lineItem,提示用户输入新值,更新lineItem ..然后构造一个新的lineItem以存储在Transaction.lineItems It isn't actually causing a bug that I can see but you should get rid of the lineItem argument entirely; 它实际上并没有引起我可以看到的错误,但是您应该完全摆脱lineItem参数; addItemLine doesn't need it. addItemLine不需要它。

3) Incidentally: 3)顺便说一句:

for (int i=0; i<2;i++){ }

loops twice, not three times. 循环两次,而不是三次。 I trust you would have caught that in testing. 我相信您会在测试中发现这一点。

4) There is also a line of code near the end of addItemLine that doesn't actually do anything! 4)在addItemLine的末尾附近还有一行代码,实际上没有任何作用! Maybe you can spot that one on your own. 也许您可以自己发现那个。

There are some other issues but those are the ones that leapt out at me. 还有其他一些问题,但是那些是我遇到的问题。

Simply put, in your method "addItemLine" you take data from 1 lineItem, overwrite it with some keyboard input, and the put in the list 2 other lineItem instances. 简而言之,在方法“ addItemLine”中,您从1个lineItem中获取数据,用一些键盘输入将其覆盖,然后在列表中放入2个其他 lineItem实例。 Then in the test code you print the original lineItem, which is not even in the list. 然后,在测试代码中打印原始的lineItem,甚至不在列表中。

The method itself iterates on nothing, just creates twice the same string "b". 该方法本身不进行任何迭代,仅创建两次相同的字符串“ b”。 I suggest you to look at some tutorials on arrays and for loops. 我建议您看一些关于数组和循环的教程。

Just a quick non-tested solution that may work. 只是一个快速的未经测试的解决方案可能会起作用。 Something is copied from your code, something is changed because your code was wrong. 从您的代码中复制了某些内容,由于您的代码错误而更改了某些内容。

// If you create this inside the method than you'll lose everything everytime you call addItemLine
private ArrayList<lineItem> lineItems;

public void addItemLine(lineItem line){
      Scanner mykey=new Scanner(System.in);
      for (int i=0; i<2;i++){
      String k= line.getItemName();
      int m= line.getQuantity();
      double d= line.getPrice();   

      System.out.println("enter item name:");
      k = mykey.next();
      line.setItemName(k);
      System.out.println("enter quantity:");
      m= mykey.nextInt();
      line.setQuantity(m);
      System.out.println("enter unit price:");
      d= mykey.nextDouble();
      line.setPrice(d);
      line.getItemName(); line.getQuantity(); line.getPrice();
      lineItems.add(new lineItem(k,m,d));
      // This doesn't have to return anything, it just adds to the list
}

// No parameteres, this should build the string for the current object
public String toString() {
    // String concatenation is not the best idea, StringBuilder is better
    StringBuilder sb = new StringBuilder();
    // If you want to print all of them then you need to iterate over the list
    for (lineItem item : lineItems){
        sb.append("Customer ID:" + this.getcustomerID() + "\n" + "Customer Name: " + this.getcustomerName());
        for (int i=0; i<2;i++){
            // Copied from your code
            sb.append("\n\n" + lin.getItemName() + "\t" + "Qty" + lin.getQuantity() + " "+ "@" + lin.getPrice() + "  "+ "\t" + "$" + lin.getTotalPrice());  
        }
    sb.append("\n);
    }
    return sb.toString();
}

It seems that you don't understand how to create a Java object, or how to keep your application model separate from your application view. 似乎您不了解如何创建Java对象,或者如何使应用程序模型与应用程序视图分离。

Here's a test run of your code, after I made some changes. 在进行一些更改之后,这是您的代码的测试运行。

Enter customer name: Gilbert
Enter customer ID: 123
Enter item name: Spinach
Enter quantity: 5
Enter unit price: .89

Customer ID:   123
Customer Name: Gilbert

Spinach Qty 5         @0.89     $4.45

Enter item name: Corn
Enter quantity: 12
Enter unit price: .29

Customer ID:   123
Customer Name: Gilbert

Corn    Qty 12         @0.29    $3.4799999999999995

Enter item name: 

First, let's look at your Java objects. 首先,让我们看一下您的Java对象。 The first Java object which you didn't include, is LineItem. 您未包含的第一个Java对象是LineItem。 Note that Java class names start with a capital letter. 请注意,Java类名称以大写字母开头。

package com.ggl.transaction;

public class LineItem {
    private String itemName;
    private int quantity;
    private double price;

    public LineItem(String itemName, int quantity, double price) {
        this.itemName = itemName;
        this.quantity = quantity;
        this.price = price;
    }

    public String getItemName() {
        return itemName;
    }

    public void setItemName(String itemName) {
        this.itemName = itemName;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public double getTotalPrice() {
        return price * quantity;
    }

}

A Java object consists of class fields, and getters and setters for the fields. Java对象由类字段以及这些字段的获取器和设置器组成。

Next, here's your Transaction class. 接下来,这是您的Transaction类。

package com.ggl.transaction;

import java.util.ArrayList;
import java.util.List;

public class Transaction {
    private List<LineItem> lineItems;
    private int customerID;
    private String customerName;

    public Transaction(int customerID, String customerName) {
        this.customerID = customerID;
        this.customerName = customerName;
        this.lineItems = new ArrayList<>();
    }

    public int getcustomerID() {
        return customerID;
    }

    public void setcustomerID(int customerID) {
        this.customerID = customerID;
    }

    public String getcustomerName() {
        return customerName;
    }

    public void setcustomerName(String customerName) {
        this.customerName = customerName;
    }

    public void addItemLine(LineItem line) {
        this.lineItems.add(line);
    }

    public void updateItem(String item, int quant, double pri) {
        LineItem l = new LineItem(item, quant, pri);
        int m = 0;
        m = l.getQuantity();
        m = m + quant;
        l.setQuantity(m);
    }

    public double getTotalPrice() {
        double totalPrice = 0;

        for (int i = 0; i < 2; i++) {
            LineItem item = lineItems.get(i);
            totalPrice = totalPrice + item.getTotalPrice();
        }
        return totalPrice;

    }

    public String getLineItem(String s, int d, double k) {
        LineItem o = new LineItem(s, d, k);
        for (int i = 0; i < 2; i++) {
            if (!s.equals(o.getItemName()))
                System.out.println("item not found");
            else
                s = (o.getItemName() + o.getQuantity() + o.getPrice());
        }
        return s;
    }

    public String toItemString(LineItem lin) {
        String b = "";

        String a = ("Customer ID:   " + this.getcustomerID() + "\n"
                + "Customer Name: " + this.getcustomerName());
        for (int i = 0; i < 2; i++) {
            b = ("\n\n" + lin.getItemName() + "\t" + "Qty " + lin.getQuantity()
                    + "         " + "@" + lin.getPrice() + "  " + "\t" + "$"
                    + lin.getTotalPrice() + "\n");
        }
        return a + b;
    }

}

I simplified your addItemLine class. 我简化了您的addItemLine类。 Code that receives input using the Scanner class belongs in your TransactionTesting class. 使用Scanner类接收输入的代码属于TransactionTesting类。

I renamed your toString method to toItemString. 我将您的toString方法重命名为toItemString。 toString is a method of the Object class. toString是Object类的方法。 Since your method has a parameter, I renamed it to lessen any confusion. 由于您的方法具有参数,因此我将其重命名以减少任何混乱。

Finally, here's your TransactionTesting class. 最后,这是您的TransactionTesting类。 I fixed it up so it would work. 我已将其修复,因此可以正常工作。 You can specify any number of line items. 您可以指定任意数量的订单项。 To stop processing, just enter a blank item name. 要停止处理,只需输入一个空白的项目名称。

package com.ggl.transaction;

import java.util.Scanner;

public class TransactionTesting {

    public static void main(String args[]) {
        Scanner mykey = new Scanner(System.in);
        System.out.print("Enter customer name: ");
        String name = mykey.nextLine().trim();
        System.out.print("Enter customer ID: ");
        int id = Integer.valueOf(mykey.nextLine().trim());

        Transaction mytrans = new Transaction(id, name);
        boolean processing = true;
        while (processing) {
            System.out.print("Enter item name: ");
            String k = mykey.nextLine().trim();
            if (k.equals("")) {
                processing = false;
            } else {
                System.out.print("Enter quantity: ");
                int m = Integer.valueOf(mykey.nextLine().trim());
                System.out.print("Enter unit price: ");
                double d = Double.valueOf(mykey.nextLine().trim());

                LineItem lineItem = new LineItem(k, m, d);
                mytrans.addItemLine(lineItem);
                System.out.println("\n" + mytrans.toItemString(lineItem));
            }
        }

        mykey.close();
    }
}

Remember, keep your application model (LineItem & Transaction) separate from your application view (TransactionTesting). 请记住,将您的应用程序模型(LineItem和事务)与应用程序视图(TransactionTesting)分开。

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

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