我有一些我需要帮助的功课。所以我不得不编写代码,其中给出了三个数字,并且通过使用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
答案 0 :(得分:0)
String.compareTo就是你想要的。
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#compareTo%28java.lang.String%29
答案 1 :(得分:0)
您可以使用Arrays.sort()
:
int[] numbers = {-40, 2, -5};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
String也是如此:
String[] names = {"Me", "You", "ABC"};
Arrays.sort(names);
System.out.println(Arrays.toString(names));
答案 2 :(得分:0)
错误在于这种情况:
else if ( ( c <= b) && ( a <= b ))
{
System.out.println("The correct order is 'c'<='a'<='b'");
}
通过此检查,您说:c
和a
小于或等于(<=
)到b
。其中,c
可以大于或小于a
。
应该{{1}}发言:else if ( ( c <= a) && ( a <= b ))
和c <= a
:a <= b
对于指定的问题,请尝试c <= a <= b
。
答案 3 :(得分: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);