2013-02-05 18 views
1

我正試圖通過讀取給定掃描儀中的物品來構建商店。構造函數必須重複(直到項目名稱爲*)從給定的掃描儀對象讀取項目並將其添加到其庫存。如何通過掃描儀搜索並用空格分隔字符串?

BreadLoaf 2.75 25

我需要一個像這樣的字符串分爲 「Breadloaf」, 「2.75」 和 「25」。然後轉到下一行並執行相同的操作,直到它顯示「*」

public class Store { 
private ArrayList<Item> inventory; 

// CONSTRUCTORS 

/* 
* Constructs a store without any items in its inventory. 
*/ 
public Store() { 

} 

/* 
* Constructs a store by reading items from a given Scanner. The constructor 
* must repeatedly (until item name is *) read items from the given scanner 
* object and add it to its inventory. Here is an example of the data (that 
* has three items) that could be entered for reading from the supplied 
* scanner: 
*/ 
public Store(Scanner keyboard) { 
    while(keyboard != null){ 

    } 
} 
+0

@vishal_aim不知道如何分割它 – JustaBreitGuy

+0

它有幫助嗎? http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html –

回答

1

請嘗試以下代碼。它最近檢查我的作品。

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

public class MyClient { 

    public static void main(String args[]) { 

     List<Item> inventory = new ArrayList<Item>(); 

     Scanner sc = new Scanner(System.in); 
     while (sc.hasNext()) { 
      String s1 = sc.nextLine(); 

      if (s1.equals("*")) { 
       break; 
      } else { 
       Scanner ls = new Scanner(s1); 
       while (ls.hasNext()) { 
        Item item = new Item(ls.next(), ls.nextFloat(), ls.nextInt()); 
        inventory.add(item); 
       } 

      } 
     } 
     System.out.println(inventory); 

    } 
} 

現在,你需要創建一個Item.java下面是項目的.java

public class Item { 
    private String name; 
    private int quanity; 
    private float price; 

    public Item(String name, float price, int quanity) { 
     this.name = name; 
     this.price = price; 
     this.quanity = quanity; 
    } 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    public int getQuanity() { 
     return quanity; 
    } 

    public void setQuanity(int quanity) { 
     this.quanity = quanity; 
    } 

    public float getPrice() { 
     return price; 
    } 

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

    @Override 
    public String toString() { 
     return "Item [name=" + name + ", quanity=" + quanity + ", price=" 
       + price + "]"; 
    } 




} 

鍵入所有庫存鍵入「*」後(星)在最後它會列出所有輸入的物品。