java - 如何在运行时传递数组的大小?
问题描述
我认为下面的代码片段可能会运行。
public class Stack {
int n;
char arr[]=new char[n];
int top=0;
void Push(char val) {
arr[top]=val;
top++;
}
}
class Solution {
public static void main(String[] args) {
Stack obj=new Stack();
obj.n=5;
obj.Push('a');
obj.Push('a');
obj.Push('a');
obj.Push('a');
}
}
但是它给出了一个ArrayOutOfBoundsException
. 为什么数组的大小没有变为 5?
解决方案
为您的堆栈使用构造函数。默认n
值设置为零。因此,您的数组正在以 0 大小创建。像下面这样的参数化构造函数应该为您完成这项工作。
public class Stack {
int n;
char arr[];
int top=0;
public Stack(int n) {
this.n = n;
this.arr = new char[n];
}
}
推荐阅读
- android - 如何从 JSONArray 中获取数据
- javascript - 无法使用 XMLHttpRequest 从数组中检索元素
- javascript - 使用 API 破坏 CORS 策略
- scala - 如何为连续运行中生成的连续数据框列生成连续唯一 ID
- c - 我对 for 循环数学有疑问;加二的幂
- python - 如何使用 pprint 将列表的一部分保存在新列表中?
- backbone.js - 如何修复 Backbone.stickit 中的“this.stickit() 不是函数”错误
- wheelnav.js - 首次加载时选择不同的选项
- javascript - 如何从 ajax-jquery 请求中获取 php 函数的结果
- c++ - 如何修复 OpenGL Superbible 第 6 版书提供的 CMake 文件