Java.lang.StringIndexOutOfBoundsException

时间:2014-02-07 03:06:58

标签: java

到目前为止,这是我的代码。我对java.lang例外感到困惑。我是编程新手。我的代码有什么问题?

import javax.swing.*;
import java.lang.Character;
import java.io.*;
public class HWCent
{
    public static void main(String args [])throws IOException
    {
        String vince = JOptionPane.showInputDialog("Enter Your File path :");
        String c = JOptionPane.showInputDialog("Enter a character");

        int NOc = 0;

        for(int v = 1; v<=c.length(); v++)
        {
            char x = c.charAt(v);
            if(Character.isSpaceChar(x))
            {
                NOc++;
            }


            char z = c.charAt(v);
            if(Character.isLetter(z))
            {
                NOc++;
            }
        }

        File file = new File(vince);

        if(!file.exists())
        {
            JOptionPane.showMessageDialog(null,"Wrong file path !");
        }
        else
        {
            JOptionPane.showMessageDialog(null, "The Number of Characters in "+ c +" is "+ NOc);

            try
            {
                RandomAccessFile gui = new RandomAccessFile(file," ");

                gui.writeBytes("The number of Characters in "+ c + " is " +NOc);
                gui.close();
            }

            catch(IOException m)
            {
                System.out.print(m.getMessage());
            }
        }


    }

}

1 个答案:

答案 0 :(得分:5)

如果你有一个长度为6的字符串,那么你可以访问的最后一个索引是5.当你使用它时

for(int v = 1; v <= c.length(); v++)

您最终尝试访问不存在的索引6。只需改为

for(int v = 0; v < c.length(); v++) // Notice < instead of <=

另外,请注意我已将v = 1更改为v = 0。 Java字符串从0开始编制索引,因此您需要从那里开始访问字符串的第一个字符。