2013-03-27 43 views
1

如何計算最大號碼並顯示它?如何找到最大號碼

import java.util.Scanner; 

public class GreatestNumber { 

    public static void main(String[] args) { 
    int [] num = new int [10]; 
    int counter; 
    int max = 0; 

    Scanner read = new Scanner(System.in); 

    for (int i=0; i<num.length; i++) 
    { 
     System.out.print("Enter StaffID to be edited:"); 
     num[i]=read.nextInt(); 
    } 
    } 
} 
+0

請正確格式化代碼,並將問題標記爲Java。 – 2013-03-27 13:10:54

+0

使用二進制搜索 – apomene 2013-03-27 13:11:45

+2

@apomene二分搜索找到排序數組中的值的位置。這不是OP正在做的事情。 – 2013-03-27 13:12:46

回答

4

您可能想在比較閱讀時的數字。另外,如果所有輸入值均爲負數,則使用0作爲max的起始值將不會打印出您想要的結果。使用Integer.MAX_VALUE代替:

int [] num = new int [10]; 
int counter; 
int max = Integer.MIN_VALUE; // use 

Scanner read = new Scanner(System.in); 

for (int i=0; i<num.length; i++) 
{ 
    System.out.print("Enter StaffID to be edited:"); 
    num[i]=read.nextInt(); 
    if (num[i] > max) 
    { 
     max = num[i]; 
    } 
} 

System.out.print("Max number is:"); 
System.out.print(max); 
+0

如果最大數字是負數,最好設置爲'num [0]'最好' – Maroun 2013-03-27 13:14:52

+0

@MarounMaroun已更新它 – 2013-03-27 13:15:16

+0

它是'Integer.MIN_VALUE'而不是'int.MIN_VALUE' – Sanchit 2013-03-27 13:18:24

1

這是你如何做到這一點:

  1. 既然你是最大的號碼後,創造出具有非常小的值的整數。

  2. 遍歷數組的元素。如果當前正在查看的元素大於當前最大的元素(在步驟1中初始化),則更新最大元素的值。目前最大的

0

跟蹤,如果你發現一個較大的數字更新,即

if (num[i] > max) 
    max = num[i]; 
0

設置一個運行變量maxInteger.MIN_VALUE。將其與數組中的每個元素進行循環比較,如果數組元素較大,則將其值複製到max。最後你有max中最大的元素。

3

除了其他用戶提供的解決方案之外,您可以從數組中創建一個List,然後使用在列表中找到最大值的現有方法。

List list = Arrays.asList(ArrayUtils.toObject(num)); 
System.out.println(Collections.max(list)); //Will print the maximum value