将文本文件输入到二维数组中

时间:2016-11-21 20:32:31

标签: java file multidimensional-array

编写一个我获取文件的方法,将文件中的前两个元素作为我的行和列,然后将其余元素作为字符串,并用它们填充二维数组。这是我的代码到目前为止,我一直有一个超出范围的例外。我应该在方法头中抛出异常。

public static String[][] input( String x) throws Exception{
    Scanner in=new Scanner(new File(x));
    String a =in.next();
    String b =in.next();
    int i = Integer.parseInt(a);
    int j = Integer.parseInt(b);
    String [][]table = new String[i][j];
    for(int count1=0;count1<table.length;count1++){
        for(int count2=0;count2<table[i].length;count2++){
            table[i][j] = in.next();
        }
    }
    return table;

    }

文件内容: 8 5 黑色红色白色蓝色橙色 红雀小熊海盗红人酿酒人 第一第二第三第四第五 Zappa Howe Hackett Metheny Latimer 在左上方向上 Anderson Cheviot Covington德里高地_Heights Grateful_Dead Genesis Phish Van_der_Graaf_Generator是的 耳眼嘴鼻涕

2 个答案:

答案 0 :(得分:0)

您使用ij代替count1count2

替换for(int count2=0;count2<table[i].length;count2++){ =&gt; for(int count2=0;count2<table[count1].length;count2++){

table[i][j] = in.next(); =&gt; table[count1][count2] = in.next();

结果代码:

public static String[][] input( String x) throws Exception{
    Scanner in=new Scanner(new File(x));
    String a =in.next();
    String b =in.next();
    int i = Integer.parseInt(a);
    int j = Integer.parseInt(b);
    String [][]table = new String[i][j];
    for(int count1=0;count1<table.length;count1++){
        for(int count2=0;count2<table[count1].length;count2++){
            table[count1][count2] = in.next();
        }
    }
    return table;

    }

答案 1 :(得分:0)

table[i][j] = in.next()替换为table[count1][count2] = in.next(),将count2<table[i].length替换为count2<table[count1].length

for(int count1=0;count1<table.length;count1++){
   for(int count2=0;count2<table[count1].length;count2++){
        table[count1][count2] = in.next();
   }
}
相关问题