新手Java

午后一小憩
  • 2.9k
package practice;

public class ArrrayParser {
    public static void main(String args []){
        String s="1,2;3,4,5;6,7,8";
        double[][]d;
        String[] sFirst=s.split(";");
        d=new double[sFirst.length][];
        for(int i=0;i<=sFirst.length;i++){
            String[] sSecond=sFirst[i].split(",");
            d[i]=new double[sSecond.length];
            for(int j=0;j<=sSecond.length;j++){
                d[i][j]=Double.parseDouble(sSecond[j]);
            }
        }
        for(int i=0;i<=d.length;i++){
            for(int j=0;j<=d[i].length;j++){
                System.out.print(d[i][j]+" ");
            }
            System.out.println();
        }
    }

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
    at practice.ArrrayParser.main(ArrrayParser.java:13)

这是为何?如何解决?

回复
阅读 2.7k
2 个回答

你确定最后没有少一个大括号?


package practice;

public class ArrrayParser {
    public static void main(String args[]) {
        String s = "1,2;3,4,5;6,7,8";
        double[][] d;
        String[] sFirst = s.split(";");
        d = new double[sFirst.length][];
        for (int i = 0; i < sFirst.length; i++) {
            String[] sSecond = sFirst[i].split(",");
            d[i] = new double[sSecond.length];
            for (int j = 0; j < sSecond.length; j++) {
                d[i][j] = Double.parseDouble(sSecond[j]);
            }
        }
        for (int i = 0; i < d.length; i++) {
            for (int j = 0; j < d[i].length; j++) {
                System.out.print(d[i][j] + " ");
            }
            System.out.println();
        }
    }
}

注意是小于,不是小于等于

d=new double[sFirst.length][];
你确定这样通过了编译?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏