try { ArrayList.add(1,99); }catch (AddIndexOutOfException e) { e.printStackTrace(); } ArrayList.display();java: 无法从静态上下文中引用非静态 方法 add(int,int)出现这个错误怎么解决
时间: 2024-01-25 21:04:54 浏览: 22
这个错误是因为你试图在静态方法中调用非静态方法add(int, int),需要创建一个ArrayList对象来调用非静态方法。以下是可能的解决方案:
```
public static void main(String[] args) {
ArrayList list = new ArrayList();
try {
list.add(1, 99);
} catch (AddIndexOutOfException e) {
e.printStackTrace();
}
list.display();
}
```
在这个例子中,我们创建了一个ArrayList对象list,并使用它来调用非静态方法add(int, int)。注意,在调用这个方法之前,我们需要使用try-catch块捕获可能抛出的AddIndexOutOfException异常。最后,我们使用list对象调用非静态方法display()来打印数组中的所有元素。
相关问题
package table; /** * @author 小蒲七七 * @version 1.0 * @date 2023/5/28 10:17 */ public class Test { public static void main(String[] args) { ArrayList arrayList = new ArrayList(); arrayList.add(1); arrayList.add(2); arrayList.add(3); arrayList.display(); // 不能在静态方法中调用非静态方法 add(int, int),需要创建一个ArrayList对象来调用非静态方法。 ArrayList list = new ArrayList(); try { list.add(1, 99); } catch (IndexOutOfException e) { e.printStackTrace(); } list.display(); } }怎么修改
可以将代码中的
```java
ArrayList list = new ArrayList();
try {
list.add(1, 99);
} catch (IndexOutOfException e) {
e.printStackTrace();
}
list.display();
```
修改为
```java
ArrayList list = new ArrayList();
try {
list.add(0, 99); // 在下标为0的位置插入元素
} catch (IndexOutOfException e) {
e.printStackTrace();
}
list.display();
```
这样就能在静态方法中调用非静态方法了,并且在下标为0的位置插入了一个元素99。
在Java中Create a list of students by reading from student_hobbies.txt and display the list.
可以按照以下步骤来实现:
1. 创建一个名为Student的类,其中包含name和hobby两个属性。
```
public class Student {
private String name;
private String hobby;
public Student(String name, String hobby) {
this.name = name;
this.hobby = hobby;
}
public String getName() {
return name;
}
public String getHobby() {
return hobby;
}
}
```
2. 创建一个名为ReadFile的类,用于从文件中读取数据并返回一个Student列表。
```
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class ReadFile {
public static List<Student> readStudentsFromFile(String fileName) {
List<Student> students = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split(":");
String name = parts[0];
String hobby = parts[1];
students.add(new Student(name, hobby));
}
} catch (Exception e) {
e.printStackTrace();
}
return students;
}
}
```
3. 在主方法中调用ReadFile类的readStudentsFromFile方法,将学生列表打印出来。
```
public class Main {
public static void main(String[] args) {
List<Student> students = ReadFile.readStudentsFromFile("student_hobbies.txt");
for (Student student : students) {
System.out.println("Name: " + student.getName() + ", Hobby: " + student.getHobby());
}
}
}
```
这样就可以从student_hobbies.txt文件中读取学生信息,并打印出来了。