2014-09-03 80 views
-3

我無法顯示數組中的最大數。這是我的代碼。當我運行它時,它給了我最多0.其餘的代碼正常工作。在java中查找最大數組

import java.util.Scanner; 

public class Assignment2 
{ 
    // method for the max 
    public static int findMax(int[] numbers, int i) 
    { 
     int max; //max variable 

     if(i > 0) 
     { 
      max = numbers[0]; 
     } 
     else 
     { 
      max = 0; 
     } 

     for(int j = 1; j < i; j++) 
     { 
      if(numbers[i] > max) 
       max = numbers[i]; 
     } 
     return max; 
    } 

    // method to add positive numbers 
    public static int computePositiveSum(int[] numbers, int i) 
    { 
     int total = 0; 

     //check if positive number 
     if (i > 0) 
     { 
      int num = (numbers[i - 1] > 0) ? numbers[i -1]:0; 
      total = num + computePositiveSum(numbers, i - 1); 
      return total; 
     } 
     else 
      return total; 
    } 


    // method to count negative numbers 
    public static int countNegative(int[] numbers, int i) 
    { 
     // if the first input is the same as 
     //length there are no negative numbers 
     if(i == numbers.length) 
     { 
      return 0; 
     } 
     // initialize the number of negatives 
     int sum = countNegative(numbers, i + 1); 
     if(numbers[i] < 0) 
     { 
      sum++; 
     } 
     // return the number of negatives 
     return sum; 
    } 


    public static void main (String[] args) 
    { 
     Scanner input = new Scanner(System.in); 

     int [] numbers = new int[100]; 
     int count = 0; 
     boolean quit = false; 

     //add numbers to array 
     for(int i= 0; i<numbers.length & quit == false; i++) 
     { 
      numbers[i]=input.nextInt(); 

      if(numbers[i] != 0) 
      { 
       count++; 
      } 
      else 
      { 
       quit = true;// exit by entering 0 
      } 
     } 
     System.out.println("The maximum number is " + findMax(numbers, count)); 
     System.out.println("The sum of the positive numbers is " + computePositiveSum(numbers, count)); 
     System.out.println("The total number of negative numbers is " + countNegative(numbers, 0)); 
    } 
} 
+0

你能提供一些更多的信息? – lewisjb 2014-09-03 00:38:34

+0

findMax方法的「i」參數應該做什麼? – 2014-09-03 00:40:05

+0

我需要打印插入陣列的最大輸入。 – jrsk8chivas 2014-09-03 00:40:38

回答

2

您正在使用的數量i,數字的計數進入,因爲索引到numbers陣列確定最大的時候,而不是j,實際的循環索引。更改

if(numbers[i] > max) 
    max = numbers[i]; 

if(numbers[j] > max) 
    max = numbers[j]; 

這是令人困惑的選擇名稱i,通常用作循環索引,爲您計數。將i重命名爲count會更易讀並且更容易混淆。

+0

是的,這是好的變量命名約定非常重要+1 – MadProgrammer 2014-09-03 00:42:02

+0

謝謝你這個工作! :)我想我對這個變量感到困惑。再次感謝 – jrsk8chivas 2014-09-03 01:47:19

-1
int a[] = { 1, 6, 7, 56, 5, 19, 26, 17 }; 

    int max = a[0]; 
    for (int i = 1; i < a.length; i++) { 

     if (max < a[i]) { 
      max = a[i]; 

     } 
     else { 
      max = max; 
     } 

    } 
    System.out.println(max); 
} 

}

+0

謝謝,我知道這會起作用,但是,這是一個類的任務,我們不能使用數組列表,但是,使用這種方法會更容易。 – jrsk8chivas 2014-09-03 01:48:10