2014-02-08 62 views
1

我目前在我的第一個學期。我有一個項目需要我建立一個用戶輸入3個字的程序,按字母順序排序並輸出中間字。我已經做了一些搜索,似乎只是返回排序2個單詞的結果。我到目前爲止有代碼來獲得用戶輸入,但我完全失去了如何按字母順序排序以及如何提示用戶輸入三個字符串。請耐心等待,因爲我對編程非常陌生。如果任何人都可以向我提供任何建議或着手整理這些最好的或最簡單的方式,我將不勝感激提示用戶輸入,然後按字母順序排序?

import java.util.Scanner; //The Scanner is in the java.util package. 

public class MiddleString { 
public static void main(String [] args){ 
Scanner input = new Scanner(System.in); //Create a Scanner object. 

String str1, str2, str3; 

System.out.println("Please enter one word words : "); //Prompt user to enter one word 
str1=input.next(); //Sets "str1" = to first word. 
str2=input.next(); //Sets "str2" = to second word. 
str3=input.next(); //Sets "str3" = to third word. 



System.out.println("The middle word is "); // Outputs the middle word in alphabetical order. 

} 
} 

請幫幫忙!

+1

提示:''''對象有一個['compareTo()'](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#compareTo%28java.lang .String%29)方法。 – Undefined

+0

*必須*您使用單獨的變量?理想情況下,將使用List(或者甚至數組)來收集這樣的輸入(因爲集合是[trivially sorted](http://stackoverflow.com/questions/708698/how-to-sort-list-alphabetically))。 – user2864740

回答

1

嘗試這樣:

String [] strings;  
int i = 0;  
System.out.println("Please enter one word words : "); //Prompt user to enter one word 
strings[i++] = input.next(); //Sets "str1" = to first word. 
strings[i++] = input.next(); //Sets "str2" = to second word. 
strings[i++] = input.next(); //Sets "str3" = to third word. 
Arrays.sort(strings); 
System.out.println("The middle word is " + strings[strings.length/2]); 
+0

我假設(可能是錯誤的),因爲OP在他/她的第一學期,也是編程新手,導師希望他們完成這個任務_without_array。 – Undefined

+0

@未定義:你可能是對的。但另一方面,在獲得用戶輸入之前,預計將被教授的數組(不是基本數據類型) – Cratylus

+0

不是我去上學的地方。 – Undefined

0

您可以進行排序(比較)在同一時間只有兩個字,是的,但這是整個排序算法的基礎。您需要循環查看您的單詞列表,並將每個單詞與每個單詞進行比較。

String[2] words = new String[2]; 
words[0] = input.next(); 
words[1] = input.next(); 
words[2] = input.next(); 

String[2] sortedWords = new String[2]; 

for (String word: words){ // outer loop 
    for (String word: words){ // inner loop to compare each word with each other 
     // logic to do the comparisons and sorting goes here 
    } 
} 

System.out.println(sortedWords[1]); 

當然,我已經爲你省去了有趣的部分,但那會讓你開始。

相關問題