Batusai
Batusai

Reputation: 149

Java.lang.StringIndexOutOfBoundsException

This is my code so far. I am confused about that java.lang exception. I'm new to programming. What could be wrong with my code?

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());
            }
        }


    }

}

Upvotes: 1

Views: 516

Answers (1)

takendarkk
takendarkk

Reputation: 3443

If you have a string with a length of 6 then the last index you can access is 5. When you used this

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

you end up trying to access an index of 6 which does not exist. Just change to

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

Also, notice I changed v = 1 to v = 0. Java Strings are indexed starting at 0 so you need to start there to access the first character of your string.

Upvotes: 5

Related Questions