首页 > 解决方案 > input.next() 用于具有多个值的一行

问题描述

我正在使用 filewriter 将地址直接从我的代码写入文件,这些值存储在文件示例(华盛顿 264 号街)的一行中。现在我想用一个构造函数将地址写入一个新的 Arraylist,该构造函数要求三个输入值(街道、数字、城市)

我已经通过这种方式完成了,但是当我输入像“公园大道”这样的街道时,它会给出错误,因为公园大道是两个词......还想知道是否有更快的“更好”方式:

@Override
public List<Adres> query(ISpecification specification) {
    File adresConnection = new File(fsConnection.getAdresConnection());
    if (specification instanceof FileSpecification) {
        if (((FileSpecification) specification).toFileQuery().equals("ALL")) {
            ArrayList<Adres> adressen = new ArrayList<>();
            try (
                    Scanner input = new Scanner(adresConnection)) {
                System.out.println("Adressen laden wordt uitgevoerd");

                while (input.hasNext()) {
                    String straat = input.next();
                    String huisNrMetKomma = input.next();
                    int huisNummer = Integer.parseInt(huisNrMetKomma.substring(0, huisNrMetKomma.length() - 1));
                    String plaats = input.next();

                    adressen.add(new Adres(straat, huisNummer, plaats));
                }

标签: javaarraysarraylistjava.util.scanner

解决方案


nextLine 读取多个单词,因此请尝试使用 nextLine(); 而不是下一个();

while (input.hasNext()) {
                String straat = input.nextLine();
                String huisNrMetKomma = input.nextLine();
                int huisNummer = Integer.parseInt(huisNrMetKomma.substring(0, huisNrMetKomma.length() - 1));
                String plaats = input.nextLine();

                adressen.add(new Adres(straat, huisNummer, plaats));
            }

推荐阅读