提问人:Perseus 提问时间:5/23/2023 最后编辑:ReilasPerseus 更新时间:5/25/2023 访问量:23
不能在数组列表中使用 add() 或制作“字符串数组”
can't use add() in array list or make "String arrays"
问:
import java.util.*;
public class Player {
ArrayList<String> paths = new ArrayList<String>(); // Create an ArrayList object
paths.add("src/images/pacman.png");
paths.add("src/images/pacmanUp.png");
// constructor and other methods
}
它说“无法解析符号添加”,我不知道我在这里错过了什么,我什至无法制作一个简单的字符串数组,然后在其中放入内容:
String[] paths =new String[4];
paths[0]="HEY";
--> “路径不是一个定义的类”
我尝试更改所有导入,但我无法解决这个问题,在所有其他类和其余代码中一切正常。
答:
0赞
Stammenator
5/23/2023
#1
这里的问题是,您尝试在任何方法或构造函数之外的类级别调用 ArrayList 上的方法 (add)。这在 Java 中是不允许的。要添加的调用应位于方法或构造函数中。
下面是如何执行此操作的示例:
import java.util.*;
公共类播放器 {
ArrayList<String> paths; // Declare the ArrayList object
public Player() {
paths = new ArrayList<String>(); // Initialize the ArrayList
paths.add("src/images/pacman.png"); // Now you can add items
paths.add("src/images/pacmanUp.png");
}
// other methods }
在此代码中,我已将 add 调用移动到 Player 类的构造函数中。现在,每当您创建一个新的 Player 对象时,它都会初始化路径 ArrayList 并向其添加两个字符串。
至于数组的问题,错误消息“paths is not a defined class”表明您的代码中可能存在语法错误,或者您正在尝试在需要类名的上下文中使用路径。
评论