我使用了这段代码。这是正确的方法吗?我想按升序对数字进行排序。有更好的方法吗?
import java.lang.Math;
public class Numbers
{
public static void main(String[] args)
{
int a=1;
int b=2;
int c=3;
if (a<b && a<c)
System.out.println("Smallest: a");
else if (a>b && a>c)
System.out.println("Biggest: a");
else if (a>b && a<c)
System.out.println("Mid: a");
else if (a<b && a>c)
System.out.println("Mid: a");
if (b<c && b<a)
System.out.println("Smallest: b");
else if (b>c && b>a)
System.out.println("Biggest: b");
else if (b>c && b<a)
System.out.println("Mid: b");
else if (b<c && b>a)
System.out.println("Mid: b");
if (c<a && c<b)
System.out.println("Smallest: c");
else if (c>a && c>b)
System.out.println("Biggest: c");
else if (c>a && c<b)
System.out.println("Mid: c");
else if (c<a && c>b)
System.out.println("Mid: c");
}
}
答案 0 :(得分:1)
您可以将三个数字存储在一个数组中,然后执行
Arrays.sort(numbers);
/* numbers[0] will contain your minimum
* numbers[1] will contain the middle value
* numbers[2] will contain your maximum
*/
这就是全部!
答案 1 :(得分:1)
一般情况下,最好使用循环和数组来表示这种类型的东西,如果你有超过3个数字它仍然可以工作。你也不必输入差不多。尝试这样的东西来寻找最小的数字。
MyArray = new int[3];
MyArray[0] = 1;
MyArray[1] = 2;
MyArray[2] = 3;
int temp = a;
for (int i = 0; i < (number of numbers to check in this case 3); i++){
if (MyArray[i] < temp){
temp = MyArray[i];
}
}
System.out.println("Smallest number is: " + temp);
答案 2 :(得分:-1)
import java.util.Scanner;
public class SortingIntegers {
public static void main (String[] args){
int num1;
int num2;
int num3;
int largerstNum;
int smallestNum;
int middleNum;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the First Integer");
num1 = sc.nextInt();
System.out.println("Pleas enter the Second Integer");
num2 = sc.nextInt();
System.out.println("Please enter the third Integer");
num3 = sc.nextInt();
if (num1 > num2){
if (num1 > num3){
largerstNum = num1;
if (num2 > num3){
middleNum = num2;
smallestNum = num3;
}else {
middleNum = num3;
smallestNum = num2;
}
}
}else {
if (num1 > num3){
middleNum = num1;
if (num2 > num3){
largerstNum = num2;
smallestNum = num3;
}else {
largerstNum = num3;
smallestNum = num2;
}
}else {
smallestNum =num1;
if (num2 > num3){
largerstNum = num2;
middleNum = num3;
}else {
largerstNum = num3;
middleNum = num2;
}
}
System.out.println("Highest Number is : " + largerstNum);
System.out.println("Smallest Number is : " + smallestNum);
System.out.println("Middle Number is : " + middleNum);
}
}
}