为什么我必须编写两次才能在数组列表中添加输入? [英] Why do I have to write twice to add an input in the Arraylist?

查看:47
本文介绍了为什么我必须编写两次才能在数组列表中添加输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public static void main(String[] args) {
    List<String> arrayList = new ArrayList<>();
    Scanner input = new Scanner(System.in);
    do {
        System.out.println("Enter a product");
        String product = input.nextLine();
        arrayList.add(product);
    }
    while (!input.nextLine().equalsIgnoreCase("q"));

    System.out.println("You wrote the following products 
");
    for (String naam : arrayList) {
        System.out.println(naam);
    }
}

我正在尝试从用户那里获取一些输入并将它们存储到arraylist中。问题是我必须写两次项才能将项添加到列表中。我想不出为什么!

推荐答案

每次写入readLine()时,都会读取一行。在此循环中,

do {
  System.out.println("Enter a product");
  String product = input.nextLine();
  arrayList.add(product);
}
while (!input.nextLine().equalsIgnoreCase("q"));

出现两次readLine(),因此每次迭代都读取两行。第一行始终添加到列表中,并且不与q核对;第二行永远不会添加到列表中,并且始终与q核对。

您应该只执行一次nextLine

while (true) {
    System.out.println("Enter a product");
    String product = input.nextLine(); // only this one time!
    if (!product.equalsIgnoreCase("q")) {
        arrayList.add(product);
    } else {
        break;
    }
}

这篇关于为什么我必须编写两次才能在数组列表中添加输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆