Hi all! I'm new to Java, so please bear with me. I'm trying to calculate the average of grades input by the user. I keep getting a exception saying that it's dividing by 0. I can't figure out why.
import java.util.Random;
import java.util.ArrayList;
import java.util.Scanner;
public class Average
{
// instance variables - this instance will get reader's name
private Scanner reader;//name from user
private Random random;//construct a Responder, declare a field type of Random
ArrayList<Integer> grade = new ArrayList<Integer>();
private String userName;//stores userName for later use.
/**
* Constructor for objects of class Calculator
* Create a responder.
* Create the Random and ArrayList object.
* Create the Scanner input object.
*/
public Average()
{
reader = new Scanner(System.in);
random = new Random();
grade = new ArrayList<Integer>();
}
/**
* Saves userName for later use.
*/
private String userName()
{
userName = reader.nextLine();
return userName;
}
/**
*Begin the program. This will print a welcome message
*and start a dialog with the user.
*
*
* @return A String typed by user.
*/
public void start()
{
{
System.out.println("Welcome to the Test Grade Average Calculator");
System.out.println("What is your name?");
userName = reader.nextLine();
System.out.println("Hello, " + userName + ". You can find the average of your test grades.");
printWelcome();
}
}
/**
* Prints a welcome message to the screen
*/
private void printWelcome()
{
System.out.println("Choose an action: (A) add a grade, (C) calculate average, (Q) quit.");
String inputLine = reader.nextLine();
if(inputLine.equalsIgnoreCase("A")){
printA();
}
if(inputLine.equalsIgnoreCase("C")){
printC();
}
if(inputLine.equalsIgnoreCase("Q")){
printQ();
}
}
/**
* Print A initializes if user input is A for Addition.
* @return A
*/
private void printA()
{
Scanner reader = new Scanner(System.in);
ArrayList<Integer> grade = new ArrayList<Integer>();
{
System.out.println("Enter a grade: ");
int n = reader.nextInt();
grade.add(n);
}
{
printWelcome();
}
}
/**
* Print C calculates average stored from arraylist.
* @return c
*/
This is where the issue is.
private void printC()
{
int sum = 0;
for(int i=0; i < grade.size(); i++){
sum = sum + (grade.get(i));
}
int average = sum / grade.size();
System.out.println("The average is " + average);
}
/**
* Print M initializes if user input is M for Multiplication.
* @return M
*/
private void printQ()
{
System.out.println("Bye!");
}
}