我正在开发一个个人项目,当我遇到麻烦时,我会编写它的“简化”版本。我正在将数据分配给 Arraylist,并且我想使用 indexOf("") 访问索引。 我已经两年没有使用 java 了,而且我很难重新使用它。
这里是主要部分,调用Plo.java
:
import plo.tre;
public class Plo
{
public static void main(String[] args)
{
tre test = new tre();
// my problem
StockDownloader.nouvel();
}
}
这是我的 tre.java 的另一个类:
import java.util.ArrayList;
public class tre
{
private ArrayList<String> open;
public tre()
{
open = new ArrayList<String>();
String s = "chaine1,chaine2, chaine a, chaine b, chaine c";
String str[] = s.split(",");
for (int i = 0; i < str.length; i++) {
open.add(str[i]);
}
}
public void nouvel()
{
System.out.println(open.get(0));
int test = open.indexOf(" chaine b");
}
}
我想做的是:1- 在 main 中调用方法 nouvel,2- 可以访问在同一类中创建的 Arraylist,但填写不同的方法。
我知道这看起来很愚蠢,但我找不到解决方案。
非常感谢您的帮助。
最佳答案
在您的 main()
方法中,您需要使用 tre
类的引用(即 test
)来调用 nouvel()
方法如下所示:
test.nouvel();
Could you explain me what was the problem?
您正在使用类名StockDownloader
(不确定它是在哪里定义的)来调用方法nouvel()
。类名只能用于调用类的静态方法/成员。要调用非static
方法,您需要使用对象引用(例如在代码中test
被称为新tre
类的对象引用您创建的对象)。
所以,问题是您需要使用对象引用来调用 Tre
类的类成员,但您没有这样做。因此,请使用 test
(这是对象的引用)来调用 nouvel()
方法。
此外,我强烈建议您按照 Java 命名标准将类重命名为 Tre
(或更有意义),即类名应以大写字母开头,以便代码可读。
还有一点是,类构造函数用于初始化实例变量,而您的代码很困惑,因此您可以重构它,如下所示:
三级:
public class Tre {
private ArrayList<String> open;
public Tre() {
open = new ArrayList<String>();//just initialize ArrayList
}
public void loadData() {//add a new method to load ArrayList
String s = "chaine1,chaine2, chaine a, chaine b, chaine c";
String str[] = s.split(",");
for (int i = 0; i < str.length; i++) {
open.add(str[i]);
}
}
public void nouvel() {
System.out.println(open.get(0));
int test = open.indexOf(" chaine b");
}
}
Plo 类:
public class Plo {
public static void main(String[] args) {
Tre test = new Tre();//create object for Tre with ref variable as test
test.loadData();//call loadData() method using test ref.
test.nouvel();//call nouvel() method using test ref.
}
}
关于java - 修改Arraylist Java,范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43419791/