简体   繁体   中英

Java: ArrayLists w/ Scanner: First element not printing

I was trying to make a program that prints out user-inputted values in an ArrayList , and for the most part, it works. Except it does not print the first element. Here is the code:

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);
    }
}

For example if, I enter jack, bob, sally, it'll print [bob, sally]

You're calling nextLine() immediately when you enter the loop, losing the previously inputted line in the process. You should use it before reading an additional value:

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

EDIT:
This, of course, means that "done" won't be added to names , so the following lines, and they should be removed:

int location = names.indexOf("done");
names.remove(location);
String x=in.nextLine();

this line outside the while loop consumes first input because as you enter the while loop , you again call x=in.nextLine(); without saving the first input, so it gets lost. Hence it doesn't gets printed because its not in the ArrayList .

Just remove String x=in.nextLine(); that is included before the while loop and your code will work fine.

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);
}

because the first element is consumed by the first x= in.nextLine(); and you never added it to the list.

Try this:

 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);

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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