简体   繁体   English

如何在Java的一行中输入多个字符串

[英]How to input multiple strings on one line in Java

我想知道如何使用JAva的Scanner类读取包含多个String单词的行。

There is no specific way to do that. 没有具体的方法可以做到这一点。 Anyway you can provide comma separated strings as below example. 无论如何,您可以提供逗号分隔的字符串,如下例所示。

public static void main(String args[]){
    Scanner in = new Scanner(System.in);
    String str = in.nextLine();
    String[] strArr = str.split(",");
    for(String s: strArr){
        System.out.println(s);
    }
}  

write a method like this: 编写这样的方法:

function String reader(Scanner s, int lines){
    String ret = "";
    for(int i = 0; i < lines; i++)
        ret += s.nextLine();
    return ret;
}

and use it like this: 并像这样使用它:

Scanner s = new Scanner(System.in);
String threeLines = reader(s, 3);

It's just a for loop that loops and read multiple lines 它只是一个for循环,循环读取多行

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

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