-1

I want to be able to input:

Avoid:
alice bob carol dave eve

and have {alice,bob,dave,eve} in the arraylist avoid

package lunch;
import java.util.ArrayList;
import java.util.Scanner;

public class LetsDoLunch {
    public static void main(String[] args){
        String s = "";
        ArrayList<String> avoid = new ArrayList<String>();

        System.out.println("Avoid:");
        Scanner sc2 = new Scanner(System.in);
        while(true){
            s = sc2.next();
            if(s.equals("")){
                break;}
            avoid.add(s);
        }
        System.out.println("done");
        for (int i = 0; i < avoid.size(); i++)
        {
            System.out.println(avoid.get(i));
        }

I'm pretty sure something it's something to do with the sc2.next(); I enter the input line after Avoid: and then nothing happens even after I press enter

D. A
  • 295
  • 1
  • 3
  • 8

2 Answers2

1

Instead of s = sc2.next() use s = sc2.nextLine()

Ezio
  • 2,837
  • 2
  • 29
  • 45
1

Try this

public static void main(String[] args) {
    String s = "";
    ArrayList<String> avoid = new ArrayList<String>();

    System.out.println("Avoid:");
    Scanner sc2 = new Scanner(System.in);
    Boolean flag = true;
    s = sc2.nextLine();
    String[] words = s.split("\\s+");
    for (int i = 0; i < words.length; i++) {
        avoid.add(words[i]);
    }
    System.out.println("done");
    for (int i = 0; i < avoid.size(); i++) {
        System.out.println(avoid.get(i));
    }

}