Java:ArrayList带扫描仪:第一个元素未打印

Java:ArrayList带扫描仪:第一个元素未打印,java,arraylist,while-loop,java.util.scanner,user-input,Java,Arraylist,While Loop,Java.util.scanner,User Input,我试图制作一个程序,在ArrayList中打印出用户输入的值,在大多数情况下,它都能正常工作。但它不打印第一个元素。代码如下: import java.util.Scanner; import java.util.ArrayList; public class Family { public static void main(String[] args){ ArrayList<String> names=new ArrayList<String>(

我试图制作一个程序,在
ArrayList
中打印出用户输入的值,在大多数情况下,它都能正常工作。但它不打印第一个元素。代码如下:

import java.util.Scanner;
import java.util.ArrayList;
public class Family {
    public static void main(String[] args){
        ArrayList<String> names=new ArrayList<String>();
        Scanner in=new Scanner(System.in);
        System.out.println("Enter the names of your immediate family members and enter \"done\" when you are finished.");
        String x=in.nextLine();
        while(!(x.equalsIgnoreCase("done"))){
            x = in.nextLine();
            names.add(x);

        }
        int location = names.indexOf("done");
        names.remove(location);
        System.out.println(names);
    }
}
import java.util.Scanner;
导入java.util.ArrayList;
公营家庭{
公共静态void main(字符串[]args){
ArrayList name=新的ArrayList();
扫描仪输入=新扫描仪(系统输入);
System.out.println(“输入直系亲属的姓名,完成后输入\“完成”);
字符串x=in.nextLine();
而(!(x.equalsIgnoreCase(“done”)){
x=in.nextLine();
名称。添加(x);
}
int location=names.indexOf(“完成”);
名称。删除(位置);
System.out.println(名称);
}
}

例如,如果我输入jack,bob,sally,它将打印[bob,sally]

,因为第一个元素被.nextLine()中的第一个
x=消耗并且您从未将其添加到列表中

试试这个:

 System.out.println("Enter the names of your immediate family members and enter \"done\" when you are finished.");
        String x="";
        while(!(x.equalsIgnoreCase("done"))){
            x = in.nextLine();
            names.add(x);

        }
while循环
外部的这一行使用第一个输入,因为当您输入
while循环
时,您再次调用
x=in.nextLine()未保存第一个输入,因此它会丢失。因此它不会被打印,因为它不在
ArrayList

只需删除.nextLine()中的
String x=in包含在
while循环之前,您的代码将正常工作

String x="";

System.out.println("Enter the names of your immediate family members and enter \"done\" " +
"when you are finished.");

while(!(x.equalsIgnoreCase("done"))){
    x = in.nextLine();
    names.add(x);
}

当您进入循环时,立即调用
nextLine()
,在此过程中丢失了先前输入的行。您应该在读取附加值之前使用它:

while (!(x.equalsIgnoreCase("done"))) {
    names.add(x);
    x = in.nextLine();            
}
编辑:
当然,这意味着
“done”
不会添加到
名称中,因此应删除以下行:

int location = names.indexOf("done");
names.remove(location);

@爱德华多登尼肯定是的。@shmosel它给出了边界的数组索引,我刚试过。查看他正在进行命名的行。删除索引将大于数组列表的大小。@EduardoDennis这些行当然应该删除-我已将其编辑到我的答案中。当然_(ツ)_/“你和@shmosel应该投票支持我的问题,因为我是对的:D@shmosel它不起作用,我把它删除了啊哈,让我们成为盟友吧,因为我们总是在Java问题中:)我甚至放弃了Votefyi,你不需要两步
indexOf()
remove()
<代码>名称。删除(“完成”)
即可。用户:这些答案对您有帮助吗?
int location = names.indexOf("done");
names.remove(location);