我需要帮助在主方法中使用数组从定义类调用方法。
public class Student{
private String id;
public void setId(String id){
this.id=id;
}
public String getId(){
return id;
}
}
主要是,有一群像这样的学生,
public static void main(String[] args){
int numOfStudent=0;
Student[] students = new Student[numOfStudent];
students[numOfStudent].setId(JOptionPane.showInputDialog("Enter id:"));
numOfStudent++;
}
我不断收到错误消息
"java:6: error: cannot find symbol
students[numOfStudent].setId(JOptionPane.showInputDialog("Enter id:"));
symbol: variable JOptionPane location: class Whatever
1 error "
这里有什么问题吗?
最佳答案
编译器认为JoptionPane
是一个变量(您没有声明)。
您需要在文件顶部导入此类。
此外,您还将收到 ArrayIndexOutOfBoundsException,因为您的数组长度为 0
,因此没有元素(在索引 0
或任何其他索引处)。
关于java - 使用数组从另一个类调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25598974/