2016-05-10 52 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; 
相關問題