2016-08-15 170 views
0

我使用此代码完成的。这是正确的方式吗?我想按升序对数字进行排序。有更好的办法吗?在Java中查找最小,最大和中间值

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

在这个问题中,你几乎不会对数组做任何事情。你是什​​么意思你想排列他们? – basic

+1

你只想获得值或“名称”?如果它只是您感兴趣的值,那么只需创建一个数组并进行排序(任何教程或数组的文档部分都可以帮助您)。它你想要的名字以及你可以创建一个包含名称和数字的对象,创建一个数组/列表和排序。 – Thomas

回答

3

扩大对史蒂夫的答案(我假设你是新来的Java,需要更完整的示例):

import java.util.Arrays; 

public class Numbers 
{ 
    public static void main(String[] args) 
    { 
    int a=3; 
    int b=2; 
    int c=1; 
    int[] numbers = {a,b,c}; 
    Arrays.sort(numbers); 
    System.out.println("The highest number is "+numbers[2]); 
    System.out.println("The middle number is "+numbers[1]); 
    System.out.println("The lowest number is "+numbers[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

一般来说,最好的办法是使用这种类型的事情循环和阵列方式如果你有超过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); 
相关问题