Вопрос

I am new to android programming and I tried to do bubble sort by inputting numbers in one EditText and the sorted numbers will be outputted on the second EditText. The program has stopped unexpectedly once I click the Sort button. Please tell me what's wrong.

package com.example.sorting;

import android.os.Bundle;
import android.app.Activity;
import android.text.Spannable;
import android.view.View; 
import android.widget.Button;
import android.widget.EditText;


public class MainActivity extends Activity{

EditText enterNum;
EditText sortedNum;
Button sortNow;

int num[] = new int[5];
int i, n, j;
int temp;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    enterNum = (EditText)findViewById(R.id.enterNum);
    sortedNum = (EditText)findViewById(R.id.sortedNum);
    sortNow = (Button)findViewById(R.id.sortNow);
    sortNow.setOnClickListener(new Button.OnClickListener(){
        public void onClick(View  v){ 
            BubbleSort();}});

}


public void BubbleSort(){

    Spannable spn=enterNum.getText();
    num[5]=Integer.valueOf(spn.toString());

            for (i=0;i<5;i++){
                for(j=i+1;j<5;j++){
                    if(num[i]>num[j]){
                        temp = num[i];
                        num[i] = num[j];
                        num[j] = temp;
                    }
                }
            }


    sortedNum.setText(String.valueOf(num[0])+String.valueOf(num[1])+String.valueOf(num[2])+String.valueOf(num[3])+String.valueOf(num[4]));


}

}

Это было полезно?

Решение

The following line should give you ArrayIndexOutOfBounds:

num[5]=Integer.valueOf(spn.toString());

Because you have declared,

int num[] = new int[5];

So your array has five elements with indexes 0,1,2,3,4
Highest index is 4

Change it to

num[4]=Integer.valueOf(spn.toString());

Also change 5 to 4 in the following loops,

for (i=0;i<4;i++){ 
                for(j=i+1;j<4;j++){

Suggestion: It is good to use num.length, instead of using absolute values such as 4 and 5

EDIT:

public void BubbleSort() {

    Spannable spn = enterNum.getText();
    for (int i = 0; i < spn.length(); i++){
        num[i] = Integer.parseInt(""+spn.charAt(i));
    }

    for (i = 0; i < num.length; i++) {
        for (j = i + 1; j < num.length; j++) {
            if (num[i] > num[j]) {
                temp = num[i];
                num[i] = num[j];
                num[j] = temp;
            }
        }
    }

    String result = "";
    for (int i = 0; i < spn.length(); i++){
        result += num[i];
    }
    sortedNum.setText(result);

}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top