[英]What is the cause of an StringIndexOutOfBoundsException in my code
[英]StringIndexOutOfBoundsException in my MapReduce code
我試圖將記錄分解為基於非字母數字字符的單詞,計算每個單詞中的第一個字母並獲得每個單詞中第一個字母的總出現次數。 下面是我試圖執行的Mapper類邏輯。
public void map(LongWritable key, Text value, Context ctx) {
String line = value.toString();
String[] split = line.split("\\W+");
String firstChar;
for(String words: split) {
firstChar = String.valueOf(words.charAt(0));
try {
ctx.write(new Text(firstChar), new IntWritable(1));
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
例外:
Error: java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:658)
at com.hadoopexp.mapper.MapperClass.map(MapperClass.java:17)
at com.hadoopexp.mapper.MapperClass.map(MapperClass.java:1)
但我在這一行的邏輯中獲得StringIndexOutOfBounds異常:
firstChar = String.valueOf(words.charAt(0));
我在輸入文件中放了一些空行,看它是否有效。 (如下)
Liverpool
Manchester
London
Toronto ? ?? !!12 32
任何人都可以幫我解決如何修復邏輯。 任何幫助都非常感謝。
拆分空字符串將返回包含空字符串的單個元素的數組。 我只是明確地檢查它:
for(String words: split) {
if (!words.isEmpty()) { // Here!
firstChar = String.valueOf(words.charAt(0));
try {
ctx.write(new Text(firstChar), new IntWritable(1));
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.