我想将多个单词读入称为输入的字符串中.可以将单词转换为数字值,例如“ 1 14 5 9 13”.用户输入后,该字符串将转换为以空格分隔的字符串数组.
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);
}
}
但是,只有第一个单词会读入字符串.
This answer建议使用nextLine()读取多字字符串,但是如果我更改它,则会引发错误.
java.lang.NumberFormatException: null
显然在我输入任何单词之前输入了一个空/空字符串.
解决方法:
您必须在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