在Android Studio中使用用户输入进行气泡排序应用 [英] bubble sort app with user input in android studio

查看:219
本文介绍了在Android Studio中使用用户输入进行气泡排序应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是android编程的新手,我试图通过在一个EditText中输入数字来进行冒泡排序,排序后的数字将输出到textview上.单击输入按钮后,程序意外停止.请告诉我什么地方出了问题"谢谢.

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 textview. The program has stopped unexpectedly once I click the input button. Please "tell me what is wrong" Thank you.

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);

  }
}

推荐答案

您尚未初始化num.使用以下代码

you don't have initialized num. use following code

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);

}

这篇关于在Android Studio中使用用户输入进行气泡排序应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆