java - 如何通过像我在这里所做的那样传递以下程序中的数组大小为 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
解决方案
您必须创建一个参数化构造函数,您将在其中传递值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);
推荐阅读
- google-apps-script - Google Apps 脚本:API 错误消息“client_id is required”
- python - How to get the logged in user ip and compare it with the previous ip, if the ip address is different, a message is issued (Django)
- swift - TableView Swipe Action Button change after clicked
- flutter - Drag and drop inside expansion tile?
- angular - 使用 Angular 9 无法正确加载数据表分页、搜索和排序
- html - Quasar Layout Two Column scrollbars
- c++ - 结构元组/在结构中包装一组可变参数模板参数值
- python - 使用python删除文件夹中的所有pdf文件
- algorithm - 在给定矩阵中查找最大模式
- symfony - 动态表单修改