0

我正在尝试制作一个计算器来计算和转换来自不同基数的数字。现在我相信这有一个非常小的问题,但我一生都找不到它。这是代码:

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)

任何人都可以识别问题吗?

4

2 回答 2

2

看起来i你的for (int i = 0; !stack.isEmpty(); i++)intoIntArr大于或等于res.length。将验证更改为

for (int i = 0; i < res.length && !stack.isEmpty(); i++) {
    //...
}

此外,在您的方法中,您需要更改变量toBase10的上限:i

for (int i = res.length - 1; i >= 0; i--) {
    //...
}
于 2013-04-21T16:19:07.970 回答
2

你应该改变这个:

for (int i = res.length; i >= 0; i--) 

至:

for (int i = res.length - 1; i >= 0; i--) 
                        ^^^

为什么

Java 中的数组是从零开始的。因此,例如,如果您有大小为10的数组,则索引将为0, 1, 2 ... 9

因此,如果您尝试到达array[10](这是.length数组的),您将获得一个ArrayIndexOutOfBoundsException.

于 2013-04-21T16:19:17.070 回答