我可以在Java中更改循环内的变量名称吗
我想在每次迭代时更改变量名称。由于创建的节点数量是动态变化的。
我尝试使用一维数组,但它返回一个空指针。我的代码如下
GenericTreeNode<String> **root1[]** = null;
for(int i=0;i<10;i++)
{
String str="child"+i;
System.out.println(str);
**root1[i]** =new GenericTreeNode<String>(str);
}
我正在使用已经构建的数据结构
public class GenericTree<T> {
private GenericTreeNode<T> root;
public GenericTree() {
super();
}
public GenericTreeNode<T> getRoot() {
return this.root;
}
public void setRoot(GenericTreeNode<T> root) {
this.root = root;
}
java或JSP中是否有其他方法可以在循环内动态更改变量名称。
I want to change the variable name with each iteration. Since the number of nodes created is dynamically changing.
I tried using one dimensional array but its returning a null pointer. My code is as follow
GenericTreeNode<String> **root1[]** = null;
for(int i=0;i<10;i++)
{
String str="child"+i;
System.out.println(str);
**root1[i]** =new GenericTreeNode<String>(str);
}
I am using already built datastructure
public class GenericTree<T> {
private GenericTreeNode<T> root;
public GenericTree() {
super();
}
public GenericTreeNode<T> getRoot() {
return this.root;
}
public void setRoot(GenericTreeNode<T> root) {
this.root = root;
}
Is there some other way in java or JSP to change the variable name dynamically inside the loop.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这一行与这一行等效:
因此您创建了一个数组变量并将其初始化为 null
,但在这里您为数组的索引分配了一个值。
这必须抛出
NullPointerException
!!。操作方法如下:
This line is equivalent to this one:
so you create an array variable and initialize it to null
but here you assign a value to the array's index.
This must throw a
NullPointerException
!!.Here's how to do it:
不,您不能更改 Java 中的变量名称。
使用数组时出现 NullPointerException,因为您尝试将值放入数组中,但数组为空。您必须使用正确数量的元素来初始化数组:
No, you can't change variable names in Java.
You got a NullPointerException when using an array because you tried to put a value in the array, and the array was null. You have to initialize the array, with the right number of elements :
您可能想这样做:
不需要“更改变量名称”。
You probably mean to do this:
There's no need to "change a variable name".
不,变量名称不能更改。尝试另一种方法(例如二维数组)来在迭代时创建另一个“变量”。
No, a variable name can't be changed. Try another method like a 2-dimensional array to create another "variable" as you're iterating.
我无法将 GenericTree 作为数组启动。后来我只用向量来解决这个问题。
I not able to initiate GenericTree as array. Later I used just vector to solve the problem.