java - 如何通过扫描仪搜索并按空格分隔字符串?

标签 java arraylist java.util.scanner

我正在尝试通过从给定的扫描仪读取项目来构建商店。构造函数必须重复(直到项目名称为 *)从给定的扫描仪对象读取项目并将其添加到其库存中。

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

    }
}

最佳答案

尝试下面的代码。我最近检查过它有效。

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




}

在最后输入所有库存类型“*”(星号)后,它将列出所有输入的项目。

关于java - 如何通过扫描仪搜索并按空格分隔字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14700119/

相关文章:

java - Android 中的自定义警报框

java - 未找到 ID 为 'sonar' 的插件?

java - 创建一个空数组列表,然后将索引设置为一个对象

java - 修改Arraylist Java,范围问题

java - eclipse可以模拟用户输入吗?

java - 使用 Hibernate 和 Spring 3 Autowiring session bean

java - 单个字符串中的多个字符串替换生成所有可能的组合

java - 对复杂类型的 ArrayList 进行排序

java - 如何用Java从文本文件中读取格式化数据

java - 扫描、字符串和 TextArea 的问题