Skip to content

Instantly share code, notes, and snippets.

@livando
Created April 6, 2011 19:24
Show Gist options
  • Save livando/906339 to your computer and use it in GitHub Desktop.
Save livando/906339 to your computer and use it in GitHub Desktop.
calculates average user input in java. must be between 2 and 25 values.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class AverageNumber {
public static void main(String[] args) {
AverageNumber ave = new AverageNumber();
try {
ave.calculateUserInputAverage();
} catch (IOException e) {
e.printStackTrace();
}
}
protected void calculateUserInputAverage() throws IOException {
System.out.println("Please input 2 to 25 numbers, enter will exit.");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s = null;
List<Float> input = new ArrayList<Float>();
while (input.size() < 25) {
s = in.readLine();
if (s.length() > 0)
try {
input.add(new Float(s));
} catch (NumberFormatException e) {
System.out.println("Unable to parse value as a number, please try again.\n");
}
else if (input.size() > 1)
break;
else
System.out.println("Please enter more than two numbers.\n");
}
System.out.println("Average: " + calculateAverage(input));
System.out.println("input: " + input.toString());
}
private String calculateAverage(List<Float> input) {
float sum = 0;
for (Float nbr : input) {
sum += nbr.floatValue();
}
return String.valueOf(sum/input.size());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment