为什么我会收到错误" java.lang.ArrayIndexOutOfBoundsException"

时间:2016-01-25 02:56:54

标签: java arrays

我是java的新手,我的老师要我写一个java程序,从输入列表中获取最高的人和最短的人以及他们的bmi。输入就像(第一个是学生的数量,第二个数字是高度:

import java.util.*;

public class Measurement {

 public static void main(String[] args) {
   int n,weight;
   double height,tallh,shorh,bmis,bmit;
   String nameh,names;
   Scanner sc = new Scanner(System.in);
   n=sc.nextInt();
   String[][] arr= new String[n][3];
   for(int i=0;i<n;i++){
     String str = sc.nextLine();
     String[] s = str.split(" ");
     arr[i][0]=s[0];
     arr[i][1]=s[1];
     arr[i][2]=s[2];
   } 
   tallh=Double.parseDouble(arr[0][1]);
   shorh=Double.parseDouble(arr[0][1]);
   bmit=0;
   bmis=0;
   nameh="";
   names="";
   for(int w=0;w<n;w++){
     if(tallh<Double.parseDouble(arr[w][1])){
       nameh=arr[w][0];
       tallh=Double.parseDouble(arr[w][1]);
       bmit=Double.parseDouble(arr[w][2])/Math.pow(tallh/100,2);
     }
     if(shorh>Double.parseDouble(arr[w][1])){
       names=arr[w][0];
       shorh=Double.parseDouble(arr[w][1]);
       bmis=Double.parseDouble(arr[w][2])/Math.pow(shorh/100,2);
     }
   }
   System.out.printf(names+"is the shortest with BMI equals to %.2f/d",bmis);
   System.out.printf(nameh+"is the tallest with BMI equals to %.2f/d",bmit);
 }
}

<script type="text/javascript">
  google.charts.load('current', {'packages':['geochart']});
  google.charts.setOnLoadCallback(drawRegionsMap);

  function drawRegionsMap() {

    var data = google.visualization.arrayToDataTable([
      ['Country'],
      ['China'],
      ['Taiwan'],
      ['Malaysia'],
    ]);

    var options = {
          backgroundColor: 'none',
          defaultColor: '#F27935'
    };

    var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));

    chart.draw(data, options);
  }
</script>

我不知道为什么会收到此错误?

1 个答案:

答案 0 :(得分:0)

您没有正确处理第一行的行尾令牌。要解决此问题,只需更改

即可
n=sc.nextInt(); // leaves a dangling end of line token

为:

n=sc.nextInt();
sc.nextLine(); // swallow the end of line token

这将吞下令牌并将事情设置为正确。