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()); } } } }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()); } } } }最满意答案
如果你有一个长度为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开始编制索引,因此您需要从那里开始访问字符串的第一个字符。
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.
更多推荐
发布评论