在android studio中用户输入冒泡排序应用程序

时间:2017-04-05 18:26:05

标签: java android sorting android-studio

我是Android编程的新手,我尝试通过在一个EditText中输入数字来进行冒泡排序,并且排序的数字将在textview上输出。单击输入按钮后,程序意外停止。请“告诉我有什么问题”谢谢。

public class MainActivity extends AppCompatActivity {

TextView Result;
EditText Input;
Button ASButton;

int i,j,temp,num[];

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

    ASButton = (Button) findViewById(R.id.button);
    Input = (EditText) findViewById(R.id.editText);
    Result = (TextView) findViewById(R.id.textView2);

    ASButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            BubbleSort();
        }
    });
}

public void BubbleSort() {

    Spannable spn = Input.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 < num.length; i++){
        result += num[i] + " ";
    }
    Result.setText(result);

  }
}

2 个答案:

答案 0 :(得分:0)

你没有初始化num。使用以下代码

public void BubbleSort() {
    Spannable spn = Input.getText();

    num = new int[spn.length()];
    int count = 0;
    for (int i = 0; i < spn.length(); i++){
        if((spn.charAt(i)+"").matches(".*\\d.*")){

            num[i] = Integer.parseInt(""+spn.charAt(i));
            count++;
        }
    }

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

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

}

答案 1 :(得分:-1)

Spannable spn = Input.getText().toString;

你的泡泡小说逻辑也错了, 正确的就像这样

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