【问题标题】:How to display numbers/strings in the correct order?如何以正确的顺序显示数字/字符串?
【发布时间】:2013-11-26 20:29:28
【问题描述】:

我有一些作业需要帮助。所以我不得不编写代码,其中给了我三个数字,并且通过使用 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

【问题讨论】:

标签: java if-statement


【解决方案1】:
【解决方案2】:

你可以使用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));

【讨论】:

    【解决方案3】:

    错误在于这种情况:

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

    通过此检查,您的意思是:ca 小于或等于 (&lt;=) 到 b。其中,c 可以大于或小于a

    应该是else if ( ( c &lt;= a) &amp;&amp; ( a &lt;= b ))发言:c &lt;= aa &lt;= bc &lt;= a &lt;= b

    对于您指定的问题,请尝试sorting他们。

    【讨论】:

      【解决方案4】:
       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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-24
        • 1970-01-01
        • 2021-08-03
        • 1970-01-01
        相关资源
        最近更新 更多