gpt4 book ai didi

java - 如何修复超出范围的字符串索引?

转载 作者:行者123 更新时间:2023-12-04 05:23:17 25 4
gpt4 key购买 nike

我的程序遇到了以下问题(仅在尝试运行它时,构建良好):

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: 
String index out of range: 57
at java.lang.String.substring(String.java:1907)
at Question7.main(Question7.java:68)

我知道网站上也有类似的问题,但我正在脑中经历这些步骤,无法弄清楚哪里出了问题。
我认为所问代码/问题的上下文不是很重要;我相信这个问题与以下几行有关:
else if (s1.substring(i,i+1).matches("[0-9]"))

if (counthyphen == 3 && countdigits == 9 && (s1.substring(i, i+1).matches("[0-9]") || s1.substring(i, i+1).matches("X")))

但是,请你自己看看。帮助将不胜感激!
public class Question7
{
public static void main(String args[])
{
//Declare and initialize.
String s1 = new String("0-471-34609-8");
int counthyphen = 0, countdigits = 0;

//Begin "for" loop.
for (int i = 0; i < s1.length()-1; i++)
{
/////////////////////////////////
// Check for missing hyphens //
if (s1.charAt(1) != '-')
{
i = s1.length();
}
else if (s1.charAt(11) != '-')
{
i = s1.length();
}

// Now add to the count values //
if (s1.charAt(i) == '-')
{
counthyphen++;
}
**else if (s1.substring(i,i+1).matches("[0-9]"))**
{
countdigits++;
}
/////////////////////////////////
}

int i = s1.charAt(s1.length()-1);
//Check if it's an ISBN and print result.
**if (counthyphen == 3 && countdigits == 9 && (s1.substring(i, i+1).matches("[0-9]") || s1.substring(i, i+1).matches("X")))**
{
System.out.print("This number is an ISBN.");
}
else
{
System.out.print("This number is NOT an ISBN.");
}
}
}

最佳答案

int i = s1.charAt(s1.length()-1);

此代码存储 ASCII codecharacter在索引处: - s1.length() - 1 , 那可以 certainly大于 maximum可访问的字符串索引。

例如 , last当前字符串中的字符是 8 ,其 ASCII code是: - 56 ,那肯定会失败。

所以, s1.substring(i, i+1)在您之后的 if 条件中会失败。

事实上,我根本不明白那条线的必要性。你为什么要使用它?

另外,您的 if-else块似乎 buggy对我来说:-
    if (s1.charAt(1) != '-')
{
i = s1.length();
}
else if (s1.charAt(11) != '-')
{
i = s1.length();
}

为什么你给 i 分配了相同的值在这两个街区有吗?

可能是 你想要这样的东西:-
    if (s1.charAt(1) != '-' || s1.charAt(11) != '-')
{
break; // Just break if not a valid string
}

关于java - 如何修复超出范围的字符串索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13482545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com