Skip to content

Instantly share code, notes, and snippets.

@scottfrazer
Created March 29, 2011 15:37
Show Gist options
  • Save scottfrazer/892580 to your computer and use it in GitHub Desktop.
Save scottfrazer/892580 to your computer and use it in GitHub Desktop.
/**
* Write a program to read a list of nonnegative integers
* and to display the largest integer, the smallest integer,
* and the average of all integers.
* The user indicates the end of the input by
* entering a negative sentinel value that is not used in
* finding the largest, smallest, and average values.
* The average value should be a value type double,
* so it can be computed with it's fractional part.
*
* @Alex Frazer
* @1.0
*/
import java.util.LinkedList;
import java.util.Scanner;
import java.util.ListIterator;
public class CS1_Frazer_X8_2
{
public static void main(String[] args)
{
// I used a linked list and used the API library to find it out.
LinkedList<Integer> num = new LinkedList<Integer>();
int minimum = 0;
int maximum = 0;
int current;
int total = 0;
double average;
System.out.println("Please enter numbers. To end list and calculate, use a negative integer.");
Scanner kbd = new Scanner(System.in);
while(true)
{
int num_read = kbd.nextInt();
if (num_read <0) break;
num.add(num_read);
}
ListIterator itr = num.listIterator();
while(itr.hasNext())
{
current = (Integer)itr.next();
if (current < minimum) minimum = current;
if (current > maximum) maximum = current;
total += current;
}
average = total/num.size();
System.out.println("The smallest number is " + minimum);
System.out.println("The largest number is " + maximum);
System.out.println("The average is " + average);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment