You have a stream of numbers of unknown length. When you hit a zero, the stream is terminated. Return the largest even number and the largest odd number.

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package XXXX;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.ArrayList;
/**This prog accepts input until user enters 0
* then find the largest odd and largest even number
*
* @author poochedi
*/
public class StreamOfNumbers {

public static void main(String[] args) throws IOException {

ArrayList oddList = new ArrayList();
ArrayList evenList = new ArrayList();
int maxOdd = 0;
int maxEven = 0;
System.out.println(“Enter the input. enter 0 to terminate”);
BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
String input = bReader.readLine();
int inputNumber = Integer.parseInt(input);

while(inputNumber !=0) {
//classify this input number
if(inputNumber%2 == 0) {

//this number is even
evenList.add(inputNumber);
}

else {

oddList.add(inputNumber);
}

//accept more input
System.out.println(“Enter the input. enter 0 to terminate”);
input = bReader.readLine();
inputNumber = Integer.parseInt(input);

}

//user entered a 0 So terminate getting the input
//Now find the maximum of the odd number and max of even number

if(!oddList.isEmpty()){

maxOdd = (int) Collections.max(oddList);
System.out.println(” Max Odd ” + maxOdd);
}
else if(oddList.isEmpty())
System.out.println(“OddList empty”);

if(!evenList.isEmpty()) {

maxEven = (int) Collections.max(evenList);
System.out.println(” Max Even ” + maxEven);
}
else if(evenList.isEmpty())
System.out.println(“Even list empty”);

}
}

Advertisements