我試圖從 csv 中獲取 minmax 值,但是 csv 上的一些值給了我一個NumberExpectedException這里是我使用的代碼
private static void minMaxValue(String path) {
try (Stream<String> stream = Files.lines(Paths.get(path)).skip(1)) {
DoubleSummaryStatistics statistics = stream
.map(s -> s.split(",")[3])
.mapToDouble(Double::valueOf)
.summaryStatistics();
System.out.println("Lowest:: " statistics.getMin());
System.out.println("Highest:: " statistics.getMax());
} catch (IOException e) {
e.printStackTrace();
}
}
我運行該方法的時間我用 try/catch 來解決它,但它仍然不是解決方案,我想替換或忽略所有特殊字符,這是給我錯誤的行:
Brittany Smith,Programme researcher broadcasting/film/video,Sawyer-Nelson,2901,0.98,8913 Mckay Loop Johnfurt CO 90828
^
uj5u.com熱心網友回復:
用 emptyString 替換所有特殊字符,您可以輕松使用:
str = str.replaceAll("[^a-zA-Z0-9]", " ");
這樣,您將只有字母和數字
uj5u.com熱心網友回復:
由于您要求的是擺脫特殊字符的正則運算式,我想只留下代表數字(-、.、\d)的字符,那么這就是您要查找的正則運算式:
String s = s.replaceAll("[^\\-\\.\\d]", ""));
uj5u.com熱心網友回復:
發布的基礎是您的實際問題是由錯誤的分隔符數量引起的。這當然是猜測,因為我們還沒有看到您的實際輸入。以下將避免此類錯誤,但無助于診斷(流對錯誤無濟于事)
private static void minMaxValue(String path) {
try (Stream<String> stream = Files.lines(Paths.get(path)).skip(1)) {
DoubleSummaryStatistics statistics = stream
.map(s -> s.split(","))
.filter(s -> s.length == 6) // Don't use magic numbers like this ;)
.map(s -> s[3])
.mapToDouble(Double::valueOf)
.summaryStatistics();
System.out.println("Lowest:: " statistics.getMin());
System.out.println("Highest:: " statistics.getMax());
} catch (IOException e) {
e.printStackTrace();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/461470.html
