很难添加值和数组长度

时间:2019-05-05 22:41:10

标签: java arrays

我正在尝试编写一些代码来计算基准百分比。该程序将收集球员的姓名,他在球队效力的年份(阵数)和开始的年份。一旦开始数组并开始信息,如果用户输入了两年,由于数组长度,我将在第二个值处收到错误消息。我如何解决这个问题?任何帮助表示赞赏。谢谢。

这是我收到的错误:“ java.lang.ArrayIndexOutOfBoundsException:2”

我尝试为每个项目创建变量,相加并除以得出基准百分比。一旦这样做,我似乎无法弄清楚每年如何打印出来。例如“ 1985年:-OBP-,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]);


  }
  }



1 个答案:

答案 0 :(得分:0)

我认为您的问题源于您可以对Years数组进行硬编码数组访问,而Years数组的长度由键盘输入定义。

years[5] = keyboard.nextInt();

因此,如果某人只玩了3年,那么year数组中只有3个元素,并且您尝试访问第6个元素,从而使您超出范围。