我的任務是以字符串數組的形式訂購BigDecimals。我的想法是使用BigDecimal的String參數構造函數,然後對其進行排序,然後使用forEach將其打印出來。這是部分代碼:如何在Java 8中從String數組創建BigDecimal流?
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String[] s = new String[n + 2];
for (int i = 0; i < n; i++) {
s[i] = sc.next();
}
Stream.of(s)
.map(i -> new BigDecimal(i))
.sorted((bg1, bg2) -> bg1.compareTo(bg2))
.forEach(System.out::println); //line 22
但我得到這個NullPointerException異常對foreach行:
Exception in thread "main" java.lang.NullPointerException
at java.math.BigDecimal.<init>(BigDecimal.java:806)
at Solution.lambda$main$1(Solution.java:20)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
at Solution.main(Solution.java:22)
我期待着從流專家聽證。
謝謝!
您正在將數組填充到第n個元素,但是您的String []具有大小'n + 2'。所以最後兩個元素是默認的'null'。在for循環中更好地將's.length'作爲謂詞。 – Flown
謝謝!掃描部分也被給出了。我不知道如何調試流,或者... – monami