Implement a program, which reads user input. If the user input is "end", the program stops reading input. The rest of the input is numbers. When the user input is "end", the program prints the average of all of the numbers.
Implement calculating the average using a stream!
My solution:
import java.util.ArrayList;
import java.util.Scanner;
public class AverageOfNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
System.out.println("Input numbers, type \"end\" to stop.");
while(true) {
String input = scanner.nextLine();
if (input.equals("end")) {
break;
}
list.add(input);
}
double average = list.stream().
mapToInt(s -> Integer.valueOf(s)).
average().
getAsDouble();
System.out.println("average of the numbers: " + average);
}
}
Functions in NetBeans, passes the internal checks of MOOC, but throws an exception in Intellij (what I use primarily)
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.valueOf(Integer.java:983)
at AverageOfNumbers.lambda$main$0(AverageOfNumbers.java:21)
at java.base/java.util.stream.ReferencePipeline$4$1.accept(ReferencePipeline.java:212)
at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1655)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.base/java.util.stream.IntPipeline.collect(IntPipeline.java:508)
at java.base/java.util.stream.IntPipeline.average(IntPipeline.java:469)
at AverageOfNumbers.main(AverageOfNumbers.java:22)
Seems to take the enter there into the list. Using .next() instead of .nextLine() makes it work in Intellij, but I'd like to understand the differences which could cause this to happen in the first place.