2013-11-26 104 views
0

我有一些我需要幫助的作業。所以我必須寫代碼給我三個數字,並且通過使用if-else語句,我必須以正確的順序顯示它們。所以我認爲我在數字的正確路徑上,但不知道如何使用字符串來顯示它。這是我迄今爲止所做的:如何以正確的順序顯示數字/字符串?

public class CS1702_Lab32 
{ 
    static public void main(String args[]) 
    { 
     int a = 9, b = -10, c = -3; 

    /* These are the six possible orders 
    * abc 
    * acb 
    * bac 
    * bca 
    * cab 
    * cba 
    */ 

    if ((a <= b) && (b <= c)) 
    { 
     System.out.println("The correct order is 'a'<='b'<='c'"); 
    } 
    else if ((a <= c) && (c <= b)) 
    { 
     System.out.println("The correct order is 'a'<='c'<='b'"); 
    } 
    else if ((b <= a) && (a <= c)) 
    { 
     System.out.println("The correct order is 'b'<='a'<='c'"); 
    } 
    else if ((b <= c) && (c <= a)) 
    { 
     System.out.println("The correct order is 'b'<='c'<='a'"); 
    } 
    else if ((c <= a) && (a <= b)) 
    { 
     System.out.println("The correct order is 'c'<='a'<='b'"); 
    } 
    else 
    { 
     System.out.println("The correct order is 'c'<='b'<='a'"); 
    } 

    } 
} 

現在我將如何去按字母順序對三個字符串做同樣的事情?我不認爲我現在應該使用數組,因爲工作表只是在條件語句中。以下是從工作表中的問題,如果是任何幫助:

Write the Java code that will solve the following problems: 

1. Given three numbers, displays them in the correct order (ascending) 
2. Given three names (e.g. name1, name2 and name3 as string variables), display them in the correct alphabetical order 
+2

您是否嘗試過使用'yourStringA.compareTo(yourStringB)'?請參閱:http://stackoverflow.com/a/6203441/362298 –

回答

0

你可以使用Arrays.sort()

int[] numbers = {-40, 2, -5}; 
Arrays.sort(numbers); 
System.out.println(Arrays.toString(numbers)); 

也是一樣的字符串:

String[] names = {"Me", "You", "ABC"}; 
Arrays.sort(names); 
System.out.println(Arrays.toString(names)); 
0

錯誤就在於此條件:

else if ((c <= b) && (a <= b)) 
    { 
     System.out.println("The correct order is 'c'<='a'<='b'"); 
    } 

通過此檢查您是在說:ca小於或等於(<=)至b。其中,c可以大於或小於a

應該else if ((c <= a) && (a <= b))說:c <= aa <= bc <= a <= b

爲了您指定的問題,嘗試sorting出來。

+0

謝謝!我現在糾正了它:) – harveysingh

0
int[] num = {11, 2, 3}; 

/*Convert the array into a list*/ 
    ArrayList<Integer> list = new ArrayList<Integer>(Arrays.aslist(num)); 

/*Sort the list*/ 
    Collections.sort(list); 

/*Same for String*/ 
    String[] str = {"b", "a", "c"}; 
    Arryslist<String> list2 = new ARrayList<String>(Arrays.aslist(str)); 

/*Sort the list*/ 
    Collections.sort(list2); 
相關問題