我通常不使用Java,而我目前正在尝试通过Java分配帮助朋友,这使我陷入困境
我正在尝试访问在对象的构造函数中创建的数组,但无法弄清楚如何访问它。
public class ADTbag {
String item = "Testing";
public ADTbag(int size) {
// This constructor has one parameter, name.
String[] bag = new String[size];
bag[0] = Integer.toString(size);
System.out.println("A bag was created with the size of " + size + " | " + bag[0]);
}
public void insert() {
/* Insert an item */
/* One Problem this public void doesn't have access to the bag var"
System.out.println(bag);
}
我觉得这是Java中的一个简单概念,但是我在Google上找不到任何对我有帮助的东西。我希望能够使用insert方法在bag或string数组对象中插入某些内容。像这样。
public static void main(String []args) {
/* Object creation */
ADTbag myBag = new ADTbag(5);
String value = "Some Value";
/* I want to do this */
mybag.insert(value);
}
}
答案 0 :(得分:1)
您需要使bag
成为类成员,以便可以在构造函数之外访问它。
答案 1 :(得分:0)
将变量定义为实例变量
public class ADTbag {
String item = "Testing";
String[] bag;
public ADTbag(int size) {
// This constructor has one parameter, name.
this.bag = new String[size];
bag[0] = Integer.toString(size);
System.okaut.println("A bag was created with the size of " + size + " | " + bag[0]);
}
public void insert() {
/* Insert an item */
/* One Problem this public void doesn't have access to the bag var"
System.out.println(bag);*/
}
}
与上面类似。
答案 2 :(得分:0)
首先,您必须使制袋领域具有全球性。之后,我们可以创建一个函数来向您的包中添加/添加新元素。这样就不必像构造函数那样使用构造函数了。
另一件事是,正如您所说的将itens插入和/或添加到“列表”中一样,可以使用ArrayList
代替标准的array
。
ArrayList是一个数据/集合结构,使您能够在运行时在同一对象上方添加,删除,设置,获取(以及其他一些操作)。如果要在数组中插入新项,就不能;为此,我们必须创建另一个具有size + 1的数组,并在设置新数组的所有元素之后。然后,这对于一个简单的操作来说很混乱。
考虑到这一点,我将为您提供一种使用此方法的方法,看看:
import java.util.ArrayList;
public class ADTbag {
/*
global field to be referenced through entire class.
We have to specify the type of objects that will be inserted
inside this list, in this case String
*/
ArrayList<String> bag;
String item = "Testing";
//constructor doesn't need parameter
public ADTbag() {
//here we init the bag list
bag = new ArrayList();
//adds your "standard item" on creating
bag.add(item);
/*
prints your msg.
- to get the size of a ArrayList just call list.size();
- to get the item from the X index just call list.get(X)
*/
System.out.println("A bag was created with the size of " + bag.size() + " | " + bag.get(0));
}
/*
you doesn't need a new method
*/
}
要使用此功能,请执行以下操作:
public static void main(String[] args) {
ADTbag myBag = new ADTbag();
myBag.bag.add("some value");
}
答案 3 :(得分:-1)
您可以在方法外部将bag声明为类,然后在构造函数中为其分配一个新的String。