Hi all,
I have an assignment for a class to read integers (until 0 is entered) from standard input into an array (including 0), then compute the minimum, sum of positive numbers, sum of numbers at even indexes and count the number of odd numbers using recursion. I've written my code but all of my answers result in 0. Can anybody help? (Sorry if my format is a little off, this is my first post!)
Code:import java.io.*;
public class Assignment9 {
public static void main (String args[]) throws IOException{
int i = 0;
int[] numbers;
numbers = new int[101];
//Read the input in and store it in an array
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader buff = new BufferedReader(input);
String line = buff.readLine();
try{
while(line.equals("0") == false && i<100){
i++;
line = buff.readLine();
numbers[i] = Integer.parseInt(line);
}
}
catch(IOException exception){
System.out.println("exception");
}
//declare variables to call recursive methods
int min = findMin(numbers, 0, i);
int pSum = computePositiveSum(numbers, 0, i);
int eSum = computeSumAtEven(numbers, 0, i);
int odd = countOdd(numbers, 0, i);
//Print the results
System.out.print("The minimum number is " +min +"\n");
System.out.print("The sum of positive numbers is " +pSum +"\n");
System.out.print("The sum of the numbers at even indexes is " +eSum +"\n");
System.out.print("The total count of odd numbers is " +odd);
}
//Recursive method for findMin
public static int findMin(int[] numbers, int startIndex, int endIndex){
if(startIndex == 0){
if(endIndex > numbers[startIndex]){
return numbers[startIndex];
}else{
if(endIndex > numbers[startIndex]){
endIndex = numbers[startIndex];
startIndex --;
}
}
}
return findMin(numbers, startIndex, endIndex);
}
//Recursive method for computePositiveSum
public static int computePositiveSum(int[] numbers, int startIndex, int endIndex){
if(startIndex == endIndex){
if(numbers[startIndex] < 0){
return 0;
}else{
return numbers[startIndex];
}
}else if(numbers[endIndex] > 0){
return computePositiveSum(numbers, startIndex, endIndex - 1) +numbers[endIndex];
}else{
return computePositiveSum(numbers, startIndex, endIndex - 1);
}
}
//Recursive method for computeSumAtEven
public static int computeSumAtEven(int[] numbers, int startIndex, int endIndex){
if(startIndex == endIndex){
if(startIndex %2 == 0){
return numbers[startIndex];
}else{
return 0;
}
}else{
if(endIndex %2 == 0){
return computeSumAtEven(numbers, startIndex, endIndex - 1) + numbers[endIndex];
}else{
return computeSumAtEven(numbers, startIndex, endIndex - 1);
}
}
}
//Recursive method for countOdd
public static int countOdd(int[] numbers, int startIndex, int endIndex){
if(startIndex == endIndex){
if(numbers[startIndex] %2 == 1){
return 1;
}else{
return 0;
}
}else{
if(numbers[startIndex] %2 == 1){
return 1 + countOdd(numbers, startIndex + 1, endIndex);
}else{
return countOdd(numbers, startIndex + 1, endIndex);
}
}
}
}
