2016-09-26 294 views
-1

下面的代码给我"java.lang.StringIndexOutOfBoundsException: String index out of range: 14"代码提供“java.lang.StringIndexOutOfBoundsException:字符串索引超出范围: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); 
     } 
    } 
} 
+0

字符串中的第15个字符不存在。你的字符串比这短。 – Bathsheba

+0

每个单字都有21个或更多字符? – SMA

+1

[Java子字符串:字符串索引超出范围]可能的重复(http://stackoverflow.com/questions/953527/java-substring-string-index-out-of-range) – xenteros

回答

0

如果您连接堆栈跟踪会更容易。无论如何,问题在于,你调用的长度小于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. 
} 
相关问题