试图将stdin的输入读入arraylist [复制]

时间:2021-06-18 21:50:17

This question already has an answer here:

这个问题在这里已有答案:

I want to be able to input:

我希望能够输入:

Avoid:
alice bob carol dave eve

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

在arraylist避免使用{alice,bob,dave,eve}

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

我很确定它与sc2.next()有关;我在避免之后进入输入行:然后在按下回车后没有任何反应

2 个解决方案

#1


0  

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

}

#2


1  

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

而不是s = sc2.next()使用s = sc2.nextLine()

#1


0  

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

}

#2


1  

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

而不是s = sc2.next()使用s = sc2.nextLine()