2013-02-05 3 views
1

주어진 스캐너에서 항목을 읽음으로써 상점을 구성하려고합니다. 생성자는 itemName이 * 일 때까지 지정된 스캐너 객체에서 항목을 읽고 인벤토리에 추가해야합니다.스캐너를 검색하고 문자열을 공백으로 나누는 방법은 무엇입니까?

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

    } 
} 

지금 당신은 입력 한 모든 항목을 나열합니다 끝에서 아래의 항목은 모든 재고 유형 "*"를 입력 한 후

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 + "]"; 
    } 




} 

된 .java 인 Item.java을 만들 (스타)가 필요합니다 .

관련 문제