我正在尝试制作一个计算器来计算和转换来自不同基数的数字。现在我相信这有一个非常小的问题,但我一生都找不到它。这是代码:
package basecalculator;
import java.util.Scanner;
public class BaseCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("num?");
int number = input.nextInt();
int numLen = String.valueOf(number).length();
int[] res = new int[numLen];
toIntArr(number, res);
for (int i = 0; i < res.length; i++) {
System.out.print(res[i] + " ");
}
System.out.println(toBase10(res));
}
public static void toIntArr(int n, int [] res){
Stack stack = new Stack();
while(n > 0) {
stack.push(n % 10);
n = n / 10;
}
for (int i = 0; !stack.isEmpty(); i++) {
res[i] = stack.pop();
}
}
public static int toBase10(int [] res) {
int sum = 0;
for (int i = res.length; i >= 0; i--) {
sum += res[i] * Math.pow(10, i); //here is where it freaks out.
}
return sum;
}
这是错误:
run:
num?
456
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at basecalculator.BaseCalculator.toBase10(BaseCalculator.java:49)
at basecalculator.BaseCalculator.main(BaseCalculator.java:28)
4 5 6 Java Result: 1
BUILD SUCCESSFUL (total time: 3 seconds)
任何人都可以识别问题吗?