-1

I am practising dynamic coding so I want to create a list for class. I hereby Initialized a list for class and want to create an array with different length for each iteration in list. But It doesnt initialize it like I expected instead its length says 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);
      }
   }
}

The array length should print 6 instead it shows 0

  • Possible duplicate of [Java order of Initialization and Instantiation](https://stackoverflow.com/questions/23093470/java-order-of-initialization-and-instantiation) – Lino Apr 17 '19 at 07:32
  • create a `setter` method that takes and sets the `N` value. This setter should also instantiate your `play` array – Scary Wombat Apr 17 '19 at 07:32
  • The arrays get initialized with the default value of `N` (which is `0`) when you call `new testcase()`, you probably want to accept a constructor parameter `N` and assign it from that constructor – Lino Apr 17 '19 at 07:33

2 Answers2

2

You have to create a parametrized constructor in which you'll pass the value of N and then initilaze the arrays. Like

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];
   }

}

And in the main methos you create object like this

  int n= . . .;//taking input from user
  testcase t=new testcase(n);
Khalid Shah
  • 3,132
  • 3
  • 20
  • 39
0

You need to write a constructor which does these assignment based on the value passed.

// Implement your constructor something like this

public Testcase(int value) {
    this.N = value;
    play = new int [value];
    // Some more assignment based on the need
}

And after that, you need to create the object instance

int N = 6;
Testcase newTestcase = Testcase(N);

NOTE: Clase name should always start with a capital letter.

Try declaring these variable like N, status, play e.t.c as private. After that assign and access them using getter() and setter().

Shravan40
  • 8,922
  • 6
  • 28
  • 48