我的 MapReduce 代码中的 StringIndexOutOfBoundsException
StringIndexOutOfBoundsException in my MapReduce code
我正在尝试根据非字母数字字符将记录分解为单词,计算每个单词中的第一个字母并获得每个单词中第一个字母的总出现次数。下面是我试图执行的 Mapper class 逻辑。
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
任何人都可以帮助我解决逻辑问题。非常感谢任何帮助。
拆分空字符串 returns 包含空字符串的单个元素的数组。我只是明确地检查它:
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();
}
}
}
我正在尝试根据非字母数字字符将记录分解为单词,计算每个单词中的第一个字母并获得每个单词中第一个字母的总出现次数。下面是我试图执行的 Mapper class 逻辑。
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
任何人都可以帮助我解决逻辑问题。非常感谢任何帮助。
拆分空字符串 returns 包含空字符串的单个元素的数组。我只是明确地检查它:
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();
}
}
}