【问题标题】:Why am I getting StringIndexOutOfBoundsException: String index out of range: 65为什么我得到 StringIndexOutOfBoundsException:字符串索引超出范围:65
【发布时间】:2016-04-27 21:37:08
【问题描述】:

我正在使用 shellsort 从输入文件中查找种群。

这是我的代码:

package assignment.pkg3;

import java.io.*;

import java.util.*;

public class Sorting{

   public static void main (String[] args) throws IOException
   {

      String[] countryArray = new String[238];
      String [] newStringArray = new String [238];
      Scanner stdIn = new Scanner(new File("C:\\Users\\talls_000\\Downloads\\CountryUnsortedFormat.txt"));

      //reads the file into the array
      while(stdIn.hasNext())
      {
         for (int i = 0; i < countryArray.length; i++)
         {
            countryArray[i] = stdIn.nextLine();
         }//end for
      }
      int j;
      int high = 65;
      String temp;
      //temp=countryArray[ i ].substring(50, 65);
      for( int gap = countryArray.length / 2; gap > 0; gap /= 2 )
      {
         for( int i = gap; i < countryArray.length; i++ )
         {
            temp=countryArray[ i ].substring(50,high);
            for( j = i; j >= gap && temp.compareTo( countryArray[ j - gap ] ) < 0; j -= gap )
            {
               countryArray[ j ] = countryArray[ j - gap ];
                countryArray[ j ] = temp;
            }


         } 
      }

      for (int i = 0; i < countryArray.length; i++)
      {
         System.out.println(countryArray[i]);
      }//end for 
   }
}

我在第 33 行收到错误:temp=countryArray[ i ].substring(50,high);

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 65
    at java.lang.String.substring(String.java:1950)
    at assignment.pkg3.Sorting.main(Sorting.java:33)

如果我将 50 更改为 0,它会起作用,但我需要从点 50 开始。 为什么会出现此错误?

【问题讨论】:

标签: java substring outofrangeexception shellsort


【解决方案1】:

似乎有些国家没有足够的长度来获取从 50 到 65 的字符。 首先,您应该检查您的 countryArray 包含的内容。只需使用调试器。

【讨论】:

    猜你喜欢
    • 2013-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-25
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    相关资源
    最近更新 更多