2016-05-10 12 views
0

所以我创建了一个发票生成器,我需要用户先说出他们将输入多少物品,然后询问物品描述(字符串),金额(int)和价格(int)。我无法为这些信息创建数组。到目前为止,我只创建了像这里它们的方法:如何创建一个获取用户输入的数组系统?

public static int itemDescription(){ 
    Scanner input=new Scanner(System.in); 
    String descr = input.nextInt();  
    return(descr); 
} 

public static int quantitySold(){ 
    Scanner input=new Scanner(System.in); 
    int quansold = input.nextInt();  
    return(quansold); 
} 

public static int unitPrice(){ 
    Scanner input=new Scanner(System.in); 
    System.out.println("Unit Price:");     
    int price = input.nextInt(); 
    return(price); 
} 

但是,如果用户有一个以上的项目投入,那么我就需要使用数组,因为这些将不能够存储超过一件数据的。 (我使他们分开的方法,因为我将需要单独的信息后来分别计算他们的税收。)

我怎么能把这些输入功能变成数组?

谢谢你提前

回答

0

如何将输入添加到列表。然后,你可以将列表转换为一个数组,如果你愿意,但你不必:

public void getInfo(int itemCount) { 
    List<String> descriptions = new ArrayList<String>(); 
    List<Integer> sold = new ArrayList<Integer>(); 
    List<Integer> unitPrices = new ArrayList<Integer>(); 

    for(int i = 0; i < itemCount; i++) { 
    descriptions.add(itemDescription()); 
    sold.add(quantitySold()); 
    unitPrices.add(unitPrice()); 
    } 
} 

这里值得注意的是 - 你itemDescription()方法返回一个int,而不是字符串。您可能想要更改它。

您还可以创建一个包含所需所有属性的Item类。并为每个属性你想要做一个item.getInput()itemCount次数!

0

首先,我会建议做一个Item类,这样的名称,数量,以及每个项目的价格可以被存储在一个单一的对象:

public class Item { 

    String description; 
    int amount; 
    int price; 

    public Item(String desc, int amt, int p) { 
     description = desc; 
     amount = amt; 
     price = p; 
    } 
} 

然后,这样的事情应该内工作你的主要方法:

Item[] items; 
String desc; 
int amt; 
int price; 

Scanner input = new Scanner(System.in); 
System.out.print("How many items? "); 

while (true) { 
    try { 
     items = new Item[input.nextInt()]; 
     break; 
    } catch (NumberFormatException ex) { 
     System.out.println("Please enter a valid integer! "); 
    } 
} 

for (int i=0; i<items.length; i++) { 
    // prompt user to input the info and assign info to desc, amt, and p 
    items[i] = new Item(desc, amt, p); 
} 

我还想指出的是,你并不需要为每个方法的独立Scanner。如果您希望包含您发布的方法,您应该获取这些值,然后将它们传递给该方法,或者将现有的Scanner传递给该方法。

0

下面是做到这一点的一种方法:

public class Invoice { 

    int ItemId; 
    String Description; 
    int Amount; 
    int Price; 

    Invoice(int itemId, String description, int amount, int price){ 

     this.ItemId = itemId; 
     this.Description = description; 
     this.Amount = amount; 
     this.Price = price; 
    } 

    public int Get_ItemId() { 
     return this.ItemId; 
    } 

    public String Get_Description() { 
     return this.Description; 
    } 

    public int Get_Amount() { 
     return this.Amount; 
    } 

    public int Get_Price() { 
     return this.Price; 
    } 
} 

.... 
ArrayList<Invoice> Invoices = new ArrayList<>(); 

// Add invoice for 2 leather belts of $10 each 
Invoices.add(new Invoice(Invoices.size(), "Leather Belt", 2, 10)); 

.... 
// Get invoice info 
int itemid = Invoices.get(0).Get_ItemId; 
相关问题