2016-08-15 74 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); 
相關問題