2017-04-05 28 views
0

我是android編程的新手,我嘗試通過在一個EditText中輸入數字來進行氣泡排序,並將排序後的數字輸出到textview上。一旦我點擊輸入按鈕,程序意外停止。請「告訴我什麼是錯的」謝謝。氣泡排序應用程序與android工作室中的用戶輸入

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

    } 
} 
+0

「告訴我什麼是錯的」。添加堆棧跟蹤。沒有人可以幫助你,如果沒有堆棧跟蹤,確切地告訴你什麼是錯的 – Zoe

+0

@sam我更新了我的答案嘗試 –

回答

-1

Spannable spn = Input.getText().toString;

和你泡SOT邏輯也是錯誤的,正確的 一個是這樣的

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

} 
+0

對不起,沒有完美的工作..它只適用於數字0-9..and當我使用空間和輸入像「5 4 9 10 15 3」它爲每個空間輸出一個0 .. – sam

+0

你以前的答案是正確的..但那只是0到9 ..我怎麼能排序比數字更大9.請幫助 – sam