简体   繁体   English

如何将用户输入的单行输出为多行?

[英]How can I output a single line of user input into multiple lines?

So basically, I'm trying to read a user input of a single line, but then split it up by space when I return the input. 因此,基本上,我试图读取一行的用户输入,但是当我返回输入时,将其按空格分开。 For example: 例如:

User input: 35 56 78 N 用户输入:35 56 78 N

Desired output: 所需的输出:

35 35

56 56

78 78

N ñ

So far, I have: 到目前为止,我有:

import java.util.Scanner;
public class GeographicCoordinatesExtractor {
    public static void main(String[] args) {
        System.out.println("Hello and welcome to my program");
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter geographical coordinates: ");
        String data = sc.next();
        sc.useDelimiter(" ");
        String value = data.split(" ")[0];

        while (sc.hasNext()) {
            String sec = sc.next();

            System.out.println(value + "\n" + sec );
        }

    }}

And im getting: 35 我得到:35

56 56

35 35

78 78

instead of: 代替:

35 35

56 56

78 78

N ñ

As you want a single line as input, why are you using Scanner#next ? 由于您希望输入一行,因此为什么要使用Scanner#next
Just go for Scanner#nextLine , then split the result, and loop the resulting String array. 只需使用Scanner#nextLine ,然后拆分结果,并循环生成的String数组。

final String data = sc.nextLine();                  // 35 56 78 N
final String[] values = data.trim().split(" ");     // [35, 56, 78, N]

for (final String v : values) {
    System.out.println(v);
}

This is because you are no " "'s (spaces) between for the last element. 这是因为最后一个元素之间没有空格。 If you have 35 56 78 N, then the first three are registered as there are spaces after them, but there is no space after the N. I would suggest using substrings. 如果您有35 56 78 N,那么前三个将被注册,因为它们后面有空格,但N之后没有空格。我建议使用子字符串。

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

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