我已经尝试了一些方法来使这段代码工作,但没有成功。
我的目标是用数字 {0, 1, 2, .... n-1}
实例化 nums[]
。 nums
没有大小,所以我使用了用零实例化 nums
的列表。请记住,结果必须是一个数组 (nums
)。
int nums[] = {}; int n = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
n = scanner.nextInt();
ArrayList<Integer> listNum = new ArrayList<Integer>();
nums = new int[listNum.size()];//instantiate nums with zeros
//nums = listNum.toArray(nums);
for (int i =0; i < n; i++){
nums[i] = i;
}
最佳答案
当你写这篇文章时:
ArrayList<Integer> listNum = new ArrayList<Integer>();
nums = new int[listNum.size()];//instantiate nums with zeros
listnum
的大小为 0,因此 nums
不会按照您的意愿进行初始化。
为什么不这样做:
nums = new int[n];
?
关于java - 将 arraylist(integer) 转换为整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33189082/