[英]This program keeps on giving me an error: Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: 4
When I write a code like this one, I always get this error. 当我编写这样的代码时,总是会出现此错误。 It is definitely building the file but is not it just gives me exemption.
它肯定是在构建文件,但不仅仅是给我豁免。 I am a beginner.
我是初学者。 Can you guys please help me out and really point out the mistake that I am making.
你们能否请我帮忙,并指出我犯的错误。
public static int binToDec(int i)
{
int[] numbers;//initialize variable
int f = 4;
String iString = "" + i;
int result = 0;
int length = iString.length();
numbers = new int[length];
int power;
for(power = iString.length(); power>=0;power--)
{
while(f == length && f >= 0)
{
numbers[power] = iString.charAt(power)^power;
}
length--;
f--;
}
for(int g = 0; g <= numbers.length; g++)//double check constraints
{
result = numbers[g] = numbers[power];
}
return result;
}
The error it is giving me is: 它给我的错误是:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(String.java:686)
at BaseConvertor.binToDec(BaseConvertor.java:34)
at BaseConvertorTester.main(BaseConvertorTester.java:10)
I also have a tester file. 我也有一个测试器文件。 Here it is:
这里是:
public class BaseConvertorTester
{
public static void main(String args[])
{
BaseConvertor.binToDec(1010);
}
}
If a String has length X
, it means that it has X
characters which are indexed starting from 0
. 如果字符串的长度为
X
,则表示它具有X
字符,这些字符的索引从0
开始。 So the last character will be at index X-1
, not X
. 因此,最后一个字符将位于索引
X-1
,而不是X
。
In your for
loop you have: 在您的
for
循环中,您有:
for (power = iString.length(); power >= 0; power--)
but this implies that, if iString
has length 4
, it will try to access the character at index 4
, which would be the fifth (non existing in the string, indeed out of range). 但这意味着,如果
iString
长度为4
,它将尝试访问索引为4
的字符,该字符将为第五个字符(字符串中不存在,实际上超出范围)。 Try with 试试看
for (power = iString.length() - 1; power >= 0; power--)
Change 更改
for(power = iString.length(); power >= 0; power--)
to 至
for(power = iString.length(); power > 0; power--)
Your loop is starting at 4 then going to 3 then 2 then 1 then 0 which is a total of 5 times when iString.length() is only 4. Changing the >= to > will exclude 0 running it only 4 times. 当iString.length()仅是4时,循环从4开始,然后依次为3、2、1然后0,这总共是5次。将> =更改为>将排除0,仅将其运行4次。
I'd also change this 我也会改变这个
String iString = "" + i;
to 至
String iString = Integer.toString(i);
better programming. 更好的编程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.