簡體   English   中英

Java.lang.StringIndexOutOfBoundsException

[英]Java.lang.StringIndexOutOfBoundsException

到目前為止,這是我的代碼。 我對該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());
            }
        }


    }

}

如果您的字符串長度為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開始,因此您需要從那里開始以訪問字符串的第一個字符。

暫無
暫無

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

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