为什么在代码“java.lang.StringIndexOutOfBoundsException”中出现此运行时异常?

为什么在代码“java.lang.StringIndexOutOfBoundsException”中出现此运行时异常?,java,Java,运行时错误: 主线程java.lang.StringIndexOutOfBoundsException中的运行时错误异常:字符串索引超出范围:0 java:658 在GFG.mainFile.java:32 导入java.util.*; 导入java.lang.*; 导入java.io.*; GFG类{ 公共静态无效主字符串参数[]引发IOException { 扫描仪sc=新的扫描系统.in; int t=sc.nextInt; whilet->0 { 字符串str=sc.nextLine

运行时错误: 主线程java.lang.StringIndexOutOfBoundsException中的运行时错误异常:字符串索引超出范围:0 java:658 在GFG.mainFile.java:32

导入java.util.*; 导入java.lang.*; 导入java.io.*; GFG类{ 公共静态无效主字符串参数[]引发IOException { 扫描仪sc=新的扫描系统.in; int t=sc.nextInt; whilet->0 { 字符串str=sc.nextLine; 字符c='\n'; int i;
对于i=0;i=97&&c=97&&c它调用的字符串中的一个位置似乎不存在str.charAti-1方法调用。当i==0,或i==str.length-1并调用charAti+1时。您可以始终放置断点并通过IDE调试应用程序

另外,异常告诉您它的位置:GFG.mainFile.java:32这是第32行 原始文件中包含所有导入、注释和包名的那一行是什么?

问题在于您的Scanner类方法。如果要在nextInt之后使用nextLine,您必须在代码中激发一个空白换行,如

sc.nextLine();
然后扫描仪将扫描字符串str=sc.nextLine

例外情况是,当扫描器接收输入时,它是作为一个空字符串接收的,例如,当您尝试查找chatAt0时,它将尝试超出空字符串的值

把下面的代码放到你的程序里

sc.nextLine(); // just for scanner to skip this line
String str=sc.nextLine();

有关更多信息,您可以参考此链接

,但如果i==0,if将首先保持,它将不会在其他条件下继续,因此,如果i>0,此str.charAti-1将正确。您能突出显示哪一行是第32行吗?