Java Average Calculator
Code for Java
// java style to import library
import java.util.Scanner;
// class must alway have 1st letter as uppercase, CamelCase is Java Class convention
public class ScanPrimitives {
public static void main(String[] args) {
Scanner input;
double sampleInputInt = 0.0;
double total = 0;
// primitive int
input = new Scanner(System.in);
System.out.print("How many numbers do you want to average: ");
try {
sampleInputInt = input.nextInt();
System.out.println(sampleInputInt);
} catch (Exception e) { // if not an integer
System.out.println("Not an int (form like 159), " + e);
}
input.close();
for (int i = 0; i < sampleInputInt; i += 1)
{
if (i == 0) {
System.out.print("Add your first number: ");
} else {
System.out.print("Add another number: ");
}
input = new Scanner(System.in);
try {
double sampleInputDouble = input.nextDouble();
System.out.println(sampleInputDouble);
total += sampleInputDouble;
} catch (Exception e) { // if not an integer
System.out.println("Not a double (form like 159 or 1.1), " + e);
}
input.close();
}
total /= sampleInputInt;
System.out.print("Your average is: ");
System.out.println(total);
}
}
ScanPrimitives.main(null);