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

    }
}
4

1 に答える 1

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 を作成する必要があります。下は Item.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 + "]";
    }




}

最後にすべての在庫タイプ「*」(星)を入力すると、入力されたすべてのアイテムがリストされます。

于 2013-02-05T04:43:32.497 に答える