I'm trying to write some code to calculate an on base percentage. The program gathers the players name, year he has played on the team (size of array) and the year he started. Once I begin the array and start the information, if the user entered two years, I receive an error right at the second value because of the arrays length. How do I get around this issue? Any help is appreciated. Thank you.
This is the error I receive: "java.lang.ArrayIndexOutOfBoundsException: 2"
I've tried creating variables for each item, adding and dividing to get the on base percentage. Once I do that, I can't seem to figure out how to print that out for each year. For example "Year 1985: -OBP-, Year 1986: -OBP-"
import java.util.Scanner;
public class RyanBaseballOBPArray
{
public static void main(String[] args)
{
int numYears;
double [] years;
String name;
int startYear;
double oBP;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter name of baseball player: ");
name = keyboard.nextLine();
System.out.print("Enter the number of years " + name +" has been playing: ");
numYears = keyboard.nextInt();
years = new double[numYears];
System.out.print("Enter " +name +" first year on the team: ");
startYear = keyboard.nextInt();
for (int index = 0; index < years.length; index++)
{
System.out.print("For Year " + (index +1 ) + "\nEnter number of hits: ");
years[1] = keyboard.nextInt();
System.out.print("For Year " + (index +1) + "\nEnter number of walks: ");
years[2] = keyboard.nextInt();
System.out.print("For Year" + (index +1) + "\nEnter the number of times player"
+ "has been hit by a pitch:");
years[3] = keyboard.nextInt();
System.out.print("For Year" + (index +1) + "\nEnter the number of at bats:");
years[4] = keyboard.nextInt();
System.out.print("For Year" + (index +1) + "\nEnter the number of sacrafice flies"
+ "that year: ");
years[5] = keyboard.nextInt();
years[0] = (years[1] + years[2] + years[3]) / years[4] + years[2] + years[3] + years[5];
}
printOnBasePercentage(name, startYear, years);
}
public static void printOnBasePercentage(String name, int startYear, double []years){
System.out.println(name + "'s On Base Percentage");
System.out.println(years[0]);
}
}