在下面的代碼中,我試圖將i中的char與i + 1中的char進行比較。我的理解是,通過使用charAt():我可以從字符串中取出字符並將其視爲整數並能夠比較兩個字符。代碼的這部分工作,但我認爲我錯過了代碼中的某些東西,因此它不打印所需的結果。除非這種對字符串中的字符進行排序的方式無效。有沒有一種方法來按字母順序對字符串進行排序而不將字符串放入數組中?
public class stringAlphabetical {
public static void main(String[] args){
String word="watch";
boolean swapped;
char temp = ' ';
do{
swapped = false;
for(int i=0;i<word.length()-1;i++){
char a = word.charAt(i);
char b = word.charAt(i+1);
if(word.charAt(i)>word.charAt(i+1)){ // if (a>b) {
temp = a;
a = b;
b = temp;
}
}
}while (swapped==true);
System.out.println(word);
}
}
什麼是您避免陣列存儲的目的?使用可變數據結構(如數組或List)是執行排序等操作的有效方法。 – dimo414
另外,你永遠不會更新'word'的值,所以這段代碼只是再次打印原始輸入。 – dimo414