简体   繁体   English

如何在Java中创建一个循环,检查单个扫描器行中的next()

[英]How do I create a loop in java that checks a single scanner line for next()

System.out.print("Enter some stuff:");
    while (input.hasNext()){
        System.out.print(input.next()+ " ");
    }

Whenever this runs, it asks the user for input, then prints it all out. 每当运行时,它都会要求用户输入,然后全部打印出来。 However, what I want, is a loop that will print out all of the tokens of a scanner. 但是,我想要的是一个循环,该循环将打印出扫描仪的所有令牌。 Then, it realizes there are no more tokens, and the loop exits. 然后,它意识到不再有令牌,并且循环退出。

Well, you'd want to read the tokens into an ArrayList , like this: 好吧,您希望将令牌读取到ArrayList ,如下所示:

List<String> store = new ArrayList<String>();
// read them all in and add them to our list
while (input.hasNext())
    store.add(input.next());
// now print them all out
for (String s: store)
    System.out.print(s+ " ");

What this does is to read them all in, and put them into the ArrayList ; 这是将它们全部读取,然后将它们放入ArrayList then, the reading loop exits when there's nothing more to read. 然后,当没有其他要读取的内容时,读取循环退出。 After that, it prints them all out. 之后,它将全部打印出来。 I think this is what you have in mind. 我认为这就是您的想法。 If you wanted to print them while you were adding them, then you could 如果要在添加它们时打印它们,则可以

List<String> store = new ArrayList<String>();
// read them all in and add them to our list
while (input.hasNext()) {
    String s = input.next();
    store.add(s);
    System.out.print(s+ " ");
}
for (String s: store) {
    // do whatever you like with them
}

Don't just copy, try to understand mate: 不只是复制,请尝试了解伴侣:

import java.io.*;
import java.util.StringTokenizer;

public class PrintStuff {

public static void main (String[] args) {
    System.out.print("Enter some shit seperated by space:");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String str=""; 
    try {
        str = br.readLine();
    } catch (IOException ioe) {
        System.out.println("IO error trying to read bitch!");
    }

    StringTokenizer st = new StringTokenizer(str);

    while (st.hasMoreElements()) {
        System.out.println(st.nextElement());
    }
}

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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