繁体   English   中英

为什么我必须写两次才能在 Arraylist 中添加一个输入?

[英]Why do I have to write twice to add an input in the Arraylist?

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 \n");
    for (String naam : arrayList) {
        System.out.println(naam);
    }
}

我试图从用户那里获得一些输入并将它们存储到 arraylist 中。 问题是我必须将项目写入两次才能将项目添加到列表中。 我不知道为什么!

而不是do-while循环仅使用while

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

每次编写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;
    }
}

发生它是因为input.nextLine()使 java 读取输入。 您应该阅读该行,然后才执行以下操作:

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

您可以使用 input.next() 读取字符串值一次,并设置一个 while 循环,并且仅当值不等于 q 时才将更多值读取到您的列表中。 如果您已经阅读了两次,则在您的 do 部分中将一个值添加到列表中,并且您在 while 部分中再次读取的值仅与 q 进行比较,因此要退出您的代码,您将丢失一个值并添加另一个,并且必须一个接一个地给出两个 q 值才能退出它。 此外,由于大多数其他用户已经给出了 nextLine 而不是 next 的答案,您可能需要检查 next 做什么以及 nextLine 做什么。 简而言之,如果您输入由分隔符(默认空格)分隔的产品名称,那么在 next 中,每个由空格分隔的值都被视为一个产品。 同样,如果您也输入不同的行。 但是,使用 nextLine,每条线作为一个整体将被添加为一个新产品。 这取决于您可能希望如何根据您的要求实现这一目标。

    public static void main(String[] args) {
        List<String> arrayList = new ArrayList<>();
        Scanner input = new Scanner(System.in);

        String product = input.next();

        while(!product.equalsIgnoreCase("q")) {
            arrayList.add(product);
            product = input.next();
        }

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM