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

时间:2016-02-02 13:59:32

标签: java

我有另一个小类,其中包含显示
的主要方法     发票,但此处的toString方法仅显示最后一项     输入,而不是三个项目名称,数量,价格和totalPrice。     我对addItemLine和toString有疑问。     谁能看到我在这里失踪的东西?     我被允许通过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));
         }
       }

5 个答案:

答案 0 :(得分:0)

像这样更改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;
    }

并从您的测试类中调用此方法如下:

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

您不需要任何参数来打印整个列表。 尝试重构一下你的代码。它可以工作,但它可以写得更好更好;)

答案 1 :(得分:0)

1)电话

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

打印出传递给它的单个lineitem。您可能希望Transaction.toString()迭代其列表Transaction.lineItems并依次打印每个项目。

实际上Transaction.toString()不需要接受lineItem参数,该方法应该只打印出类实例的内部。

2)Transacton.addItemLine()中存在类似的混淆。它接受lineItem,提示用户输入新值,更新lineItem ..然后构造一个新的lineItem存储在Transaction.lineItems中。它实际上并没有导致我能看到的错误,但你应该完全摆脱lineItem参数; addItemLine并不需要它。

3)顺便说一句:

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

循环两次,而不是三次。我相信你会在测试中发现它。

4)addItemLine末尾附近还有一行代码,它实际上并没有做任何事情!也许你可以自己发现那个。

还有一些其他问题,但那些问题突然出现在我身上。

答案 2 :(得分:0)

简单地说,在你的方法“addItemLine”中,你从1 lineItem获取数据,用一些键盘输入覆盖它,并在列表2 其他 lineItem实例中输入。 然后在测试代码中打印原始的lineItem,它甚至不在列表中。

方法本身无任何迭代,只创建两次相同的字符串“b”。 我建议你看看有关数组和for循环的一些教程。

答案 3 :(得分:0)

只是一个可以运行的快速未经测试的解决方案。从代码中复制了一些东西,因为代码错误而改变了一些东西。

// 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();
}

答案 4 :(得分:0)

您似乎不了解如何创建Java对象,或者如何将应用程序模型与应用程序视图分开。

在我做了一些更改之后,这是您的代码的测试运行。

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: 

首先,让我们看看你的Java对象。您没有包含的第一个Java对象是LineItem。请注意,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;
    }

}

Java对象由类字段以及字段的getter和setter组成。

接下来,这是您的交易类。

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;
    }

}

我简化了你的addItemLine类。使用Scanner类接收输入的代码属于TransactionTesting类。

我将toString方法重命名为toItemString。 toString是Object类的一个方法。由于您的方法有参数,我将其重命名以减少任何混淆。

最后,这是您的TransactionTesting类。我把它修好了所以它会起作用。您可以指定任意数量的订单项。要停止处理,只需输入空白项目名称。

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();
    }
}

请记住,将应用程序模型(LineItem&amp; Transaction)与应用程序视图(TransactionTesting)分开。