首页 > 解决方案 > 如何通过像我在这里所做的那样传递以下程序中的数组大小为 6?

问题描述

我正在练习动态编码,所以我想为班级创建一个列表。我特此为类初始化了一个列表,并希望为列表中的每次迭代创建一个具有不同长度的数组。但它并没有像我预期的那样初始化它,而是它的长度为 0。

import java.io.*;
import java.util.*;
class testcase
{
   int N;
   int play []= new int [N];
   int villain[]=new int [N];
   String status;
}
public class Main {
   public static void main(String args[] ) throws Exception {
      List<testcase> caseno=new ArrayList<testcase>();
      Scanner sc=new Scanner(System.in);
      int n1=1;
      //int n1=sc.nextInt();
      int i,j;
      testcase t;
      for(i=0;i<n1;i++)
      {
      int n=6;
      //int n=sc.nextInt();
      t=new testcase();
      t.N=n;
      System.out.println(t.N+" "+t.play.length);
      }
   }
}

数组长度应打印 6 而不是显示 0

标签: java

解决方案


您必须创建一个参数化构造函数,您将在其中传递值N然后初始化数组。像

class testcase // Name should be in PASCAL 
{
   int N;
   int [] play;
   int [] villain;
   String status;

   public testcase (int n) { // Constructor 
      this.N=n;
      play = new int [N];
      villain=new int [N];
   }

}

在主要方法中,您创建这样的对象

  int n= . . .;//taking input from user
  testcase t=new testcase(n);

推荐阅读