简体   繁体   English

从stdin读取多字符串

[英]Read a multi-word string from stdin

I want to read multiple words into a string called input . 我想将多个单词读入一个名为input的字符串中。 The words can be casted into numeric values like "1 14 5 9 13" . 单词可以输入数字值,如"1 14 5 9 13" After the user input, the string will be converted into a string array separated by spaces. 用户输入后,字符串将转换为由空格分隔的字符串数组。

public class ArraySum {

  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int n = Integer.parseInt(scanner.next());
    System.out.println("Please enter "+n+" numbers");
    String input = scanner.next(); // ERROR: only the first word is read
    String[] inputs  = input.split("\\s+"); 
    int sum=0;
    for (int i =0; i<inputs.length; i++){
        if (!inputs[i].equals(""))
            sum+= Long.parseLong(inputs[i]);
    }
    System.out.print(sum);
}
}

However only the first word is read into the string. 但是只有第一个字被读入字符串。

This answer suggests using nextLine() to read a multi-word string, but if I change it, an error was thrown. 这个答案建议使用nextLine()来读取多字符串,但如果我改变它,则会抛出错误。

java.lang.NumberFormatException: null java.lang.NumberFormatException:null

Apparently an empty/null string was inputted before I entered any word. 在我输入任何单词之前,显然输入了一个空/空字符串。

You have to use nextLine after nextInt to clear your Scanner like this : 您必须在nextInt之后使用nextLine来清除您的扫描仪,如下所示:

int n = scanner.nextInt();//read your int
scanner.nextLine();//clear your Scanner
System.out.println("Please enter " + n + " numbers");
String input = scanner.nextLine();//read your String example 12 55 66

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

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