Java - 将构造函数的参数传递给数组

时间:2015-10-12 07:13:15

标签: java arrays object constructor

所以基本上我将3个字符串传递给我的构造函数,然后将它们放在我的对象/类中的已经制作的数组中,我在尝试解决这个问题时遇到了一些麻烦。

这是我的对象类

public class results {
String[] matchnumber = new String[9];
String[] score1 = new String[9];
String[] score2 = new String[9];
int i = 0;



public results() {


}

  public void addResults(String token, String token2, String token3) {
        matchnumber[i] = token;
        score1[i] = token2;
        score2[i] = token3;

        i++;
      }

这是我的主要课程

>  do     { 
>             System.out.println("Enter the current Round number between 1-26");
>             roundnumber = kb.nextInt();   
>             } while (roundnumber <= 0 || roundnumber >= 27);  
>              results[] resultsarray = new results[(roundnumber)];
>     
>           for (int i = 0; i < resultsarray.length; i++) {
>               File myFiles2 = new File("Round" + (i+1) +".txt");
>               Scanner inputFiles2 = new Scanner(myFiles2);
>       
>            while (inputFiles2.hasNext()) {
>               String str2 = inputFiles2.nextLine();
>               String[] token = str2.split(",");
>               System.out.println(token[0] + " " + token[1]+ " " + token[2]);
>               resultsarray[i].addResults(token[0], token[1], token[2]); (NULL EXCEPTION ON THIS LINE)
>          }
>          }

正如您所见,我正在扫描文本文件以获取3个字符串(文本文件包含数据行)。我需要帮助的是在我的对象中传递3个字符串标记,然后将其保存为数组,然后将下一批3个字符串处理到下一个数组索引中,直到我用完当前文本文件中的字符串,然后下一个打开文本文件并创建结果对象的新实例并冲洗并重复。所以,我甚至接近或完全偏离轨道大声笑。

1 个答案:

答案 0 :(得分:0)

您不应该在results构造函数中为数组赋值,因为构造函数只接受数组的单个索引的值,而您当前的代码只使用第一个(0)索引每个阵列。

您应该使用不带参数的构造函数,并使用不同的方法将数据添加到数组中。

你的内循环将如下所示:

       resultsarray[i] = new results();
       while (inputFiles2.hasNext()) {
           String str2 = inputFiles2.nextLine();
           String[] token = str2.split(",");
           System.out.println(token[0] + " " + token[1]+ " " + token[2]);
           resultsarray[i].addResults(token[0], token[1], token[2]);
       }

其中addResults是一个包含旧构造函数逻辑的新方法。