由于未知原因返回ArrayIndexOutOfBoundsException错误

时间:2016-11-11 06:42:57

标签: java arrays bubble-sort

我正在尝试创建一个基本的冒泡排序程序但是在某些时候数组尝试引用第11个位置,尽管数组是10长并且我不确定它何时发生

int Last, i = 0, Temp;
    int[] Numbers = new int[10];
    String[] NumbersString = new String[10];
    String initialString = TextBox.getText();
    NumbersString = initialString.split(" ");
    while(i<10){
        Numbers[i] = Integer.parseInt(NumbersString[i]);
        i = i + 1;
    }
    Last = 9;
    Boolean Swapped = true;
    while(Swapped = true) {
        Swapped = false;
        i = 0;
        while(i < Last) {
                if(Numbers[i] > Numbers[i+1]){
                Temp = Numbers[i];
                Numbers[i] = Numbers[i+1];
                Numbers[i+1] = Temp;
                Swapped = true;
                }
            i = i + 1;
        }
        Last = Last-1;
    }
    String Result = Numbers[0] + " " + Numbers[1] + " " + Numbers[2] + " " + Numbers[3] + " " + Numbers[4] + " " + Numbers[5] + " " + Numbers[6] + " " + Numbers[7] + " " + Numbers[8] + " " + Numbers[9];
    ResultText.setText(Result);

2 个答案:

答案 0 :(得分:1)

更改

 while(Swapped = true) {

 while(Swapped == true) {

正在发生的事情是Last首先包装到Negative,然后当它达到最小负数时,它将包装到Integer.MAX_VALUE,然后i将超过9

答案 1 :(得分:0)

只是尝试将数组的长度放在这里。

int Last, i = 0, Temp;
    int[] Numbers = new int[10];
    String[] NumbersString = new String[10];
    String initialString = "1";
    NumbersString = initialString.split(" ");
    while (i < NumbersString.length) { // <-- I change it to NumbersString.length
        Numbers[i] = Integer.parseInt(NumbersString[i]);
        i = i + 1;
    }
    Last = Numbers.length-1; // <-- I change it to Numbers.length-1
    Boolean Swapped = true;
    while (Swapped) { // <-- I change it to Swapped only because your Swapped is a Boolean type, no need to equals it into true.
        Swapped = false;
        i = 0;
        while (i < Last) {
            if (Numbers[i] > Numbers[i + 1]) {
                Temp = Numbers[i];
                Numbers[i] = Numbers[i + 1];
                Numbers[i + 1] = Temp;
                Swapped = true;
            }
            i = i + 1;
        }
        Last = Last - 1;
    }
    String Result = Numbers[0] + " " + Numbers[1] + " " + Numbers[2] + " " + Numbers[3] + " " + Numbers[4] + " "
            + Numbers[5] + " " + Numbers[6] + " " + Numbers[7] + " " + Numbers[8] + " " + Numbers[9];
    System.out.println(Result);
}