Click to See Complete Forum and Search --> : str to num error


crazycoder
09-18-2006, 06:00 PM
I wanted to change a string to a number so I made this code:

public class strtonum {
public static void main(String[] arge) {
System.out.println(strtonum("1234"));
}

static long strtonum(String str) {
str = str.trim();
long n = 0;
char[] c = str.toCharArray();
for (int i = 0; i <= str.length(); i++) {
short t;
switch(c[i]) {
case '0':
t = 0;
break;
case '1':
t = 1;
break;
case '2':
t = 2;
break;
case '3':
t = 3;
break;
case '4':
t = 4;
break;
case '5':
t = 5;
break;
case '6':
t = 6;
break;
case '7':
t = 7;
break;
case '8':
t = 8;
break;
case '9':
t = 9;
break;
default:
return -1;
}
n += t * Math.pow(10, str.length() - i);
}
return n;
}
}

it gives me this error:
java.lang.ArrayIndexOutOfBoundsException: 4

crazycoder
09-18-2006, 06:09 PM
Okay, that was really stupid of me. I completely forgot about Integer.parseInt("123");

agent_x91
09-20-2006, 03:29 AM
:p Remember to check if the string is null before using Integer.parseInt(), as well. Also, Double.parseDouble() may be useful for you. :D

drch
09-23-2006, 02:09 AM
Okay, that was really stupid of me. I completely forgot about Integer.parseInt("123");

Despite the obfuscated code, the problem was with your loop. When processing a string, you want i < str.length(), not <=, because strings are 0 indexed.