到目前为止,这是我的代码。我对 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 开始,因此您需要从那里开始才能访问字符串的第一个字符。
关于Java.lang.StringIndexOutOfBoundsException异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21618538/