【问题标题】:code gives "java.lang.StringIndexOutOfBoundsException: String index out of range: 14"代码给出“java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:14”
【发布时间】:2017-02-03 18:32:04
【问题描述】:

下面的代码给了我"java.lang.StringIndexOutOfBoundsException: String index out of range: 14"

请指导我了解我的代码有什么问题。

public class max_temp {

    public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable> {

        private final static IntWritable one = new IntWritable(1);
        private Text word = new Text();
        public String y;
        public String a;
        public Double t;

        public void map(Object key, Text value, Context context) throws IOException, InterruptedException {

            StringTokenizer itr = new StringTokenizer(value.toString());
            while (itr.hasMoreTokens()) {
                word.set(itr.nextToken());
                y = word.toString();
                a = y.substring(7,14);
                t = Double.parseDouble((y.substring(35,41).trim()));

                word.set(a);              

               // 27516201501012.424-156.6171.32-18.3-21.8-20.0-1   9.90.00.00C-19.2-24.5-21.983.973.777.                                
               context.write(word, one);
           }
       }
   }

   public static class IntSumReducer extends Reducer<Text,IntWritable,Text,IntWritable> {
       private IntWritable result = new IntWritable();

        public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {

            int sum = 0;
            for (IntWritable val : values) {
                sum += val.get();
            }
            result.set(sum);
            context.write(key, result);
        }
    }
}

【问题讨论】:

  • 字符串中的第 15 个字符不存在。你的字符串比那个短。
  • 每个单词有21个字符或更多吗?
  • 我的回答对您有帮助吗?如果是,请点击答案分数下方的灰色勾号,将其标记为解决方案。

标签: java string hadoop mapreduce


【解决方案1】:

如果你附加了堆栈跟踪会更容易。无论如何,问题是,您正在调用长度小于 15 的 Stringsubstring(7,14)。Java 不知道该怎么做,因此会引发异常。

问题在于您的应用逻辑。如果您使用substring(7,14),您必须确保String 足够长或使用try-catch 块。

try {
    String s = s.substring(7,14);
} catch (StringIndexOutOfBoundsException e) {
    //somehow process the situation in which the string is too short.
}

【讨论】:

    猜你喜欢
    • 2012-03-02
    • 1970-01-01
    • 2016-02-25
    • 2018-11-14
    • 1970-01-01
    • 1970-01-01
    • 2014-04-14
    • 1970-01-01
    • 2019-05-22
    相关资源
    最近更新 更多