为什么Java不打印行中的所有单词(当单词被添加到ArrayList时)?

She*_*don 2 java arraylist println

当将用户输入打印为一行中的单个单词时,我得到该行中所有单词的打印输出.

System.out.println(userInput.next());
Run Code Online (Sandbox Code Playgroud)

但是,当我将单个单词添加到ArrayList时,我似乎得到了随机单词:

 al.add(userInput.next());
Run Code Online (Sandbox Code Playgroud)

有人可以向我解释发生了什么事吗?

谢谢.

这是代码的完整副本:

import java.util.*;


public class Kwic {
    public static void main(String args[]){

        Scanner userInput = new Scanner(System.in);
        ArrayList<String> al = new ArrayList<String>();


        while(userInput.hasNext()){
            al.add(userInput.next());
            System.out.println(userInput.next());
        }


    }
}
Run Code Online (Sandbox Code Playgroud)

gtg*_*ola 9

while(userInput.hasNext()){
    al.add(userInput.next());   //Adding userInput call to ArrayList
    System.out.println(userInput.next());  //Printing another userInput call
}
Run Code Online (Sandbox Code Playgroud)

不是打印存储在ArrayList中的值,而是实际上是对userInput.next()的另一个调用

调整

@ Sheldon这对我有用.

public static void main(String[] args) {
    Scanner userInput = new Scanner(System.in);
    ArrayList<String> al = new ArrayList<String>();
    while(userInput.hasNext()){
        al.add(userInput.next());
        System.out.println(al);  //LINE CHANGED FROM YOUR QUESTION
    }

}
Run Code Online (Sandbox Code Playgroud)

我用输入测试了你的代码 1 2 3 4 5 6 7 8 9 0

然后我按下回车并得到:

2 4 6 8 0

userInput.next()在添加到ArrayList的那个和System.out.println捕获的那个之间交替.


Joã*_*lva 5

因为从扫描仪next()消耗下一个令牌.因此,当你有:

        al.add(userInput.next());
        System.out.println(userInput.next());
Run Code Online (Sandbox Code Playgroud)

您实际上是从扫描仪中消耗了两个令牌.第一个是被添加到ArrayList其他被打印到System.out.一种可能的解决方案是将令牌存储在局部变量中,然后将其添加到阵列并打印它:

    while (userInput.hasNext()) {
        String token = userInput.next();
        al.add(token);
        System.out.println(token);
    }
Run Code Online (Sandbox Code Playgroud)