簡體   English   中英

代碼給出“java.lang.StringIndexOutOfBoundsException:字符串索引超出范圍:14”

[英]code gives "java.lang.StringIndexOutOfBoundsException: String index out of range: 14"

以下代碼給了我"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 的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.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM