我無法顯示數組中的最大數。這是我的代碼。當我運行它時,它給了我最多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));
}
}
你能提供一些更多的信息? – lewisjb 2014-09-03 00:38:34
findMax方法的「i」參數應該做什麼? – 2014-09-03 00:40:05
我需要打印插入陣列的最大輸入。 – jrsk8chivas 2014-09-03 00:40:38