Skip to content

Instantly share code, notes, and snippets.

@TheLouisHong
Created October 21, 2013 14:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheLouisHong/7084980 to your computer and use it in GitHub Desktop.
Save TheLouisHong/7084980 to your computer and use it in GitHub Desktop.
#7 of Homework
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
float sum = 0;
int count = 0;
mainLoop: while (true) {
System.out.print("Input a number, -1 to find average: ");
try {
float input = keyboard.nextFloat();
if (input != -1) {
sum += input;
count += 1;
System.out.println("The sum of of the " + count + " numbers is " + (int) sum);
} else {
System.out.println("The average of these numbers are " + (sum / count));
sum = 0;
count = 0;
}
} catch (Exception e) {
System.out.println("Invalid input, please enter a float or int");
keyboard.next();
continue mainLoop;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment