Java 为什么在For Each循环中Station对象为Null?
我正在编写一个基本程序,它可以遍历一组对象。然后,我为每个循环创建一个值,并根据用户输入设置数组中每个对象的值。但是,我在用于存储对象数组值的对象上收到一个空指针异常 这是我的密码: 导入javax.swing.*Java 为什么在For Each循环中Station对象为Null?,java,arrays,loops,Java,Arrays,Loops,我正在编写一个基本程序,它可以遍历一组对象。然后,我为每个循环创建一个值,并根据用户输入设置数组中每个对象的值。但是,我在用于存储对象数组值的对象上收到一个空指针异常 这是我的密码: 导入javax.swing.* public class Calculation { public static Stations[] createStationArray(){ int numOfStations; String string = JOptionPane.showInputDialog(nul
public class Calculation {
public static Stations[] createStationArray(){
int numOfStations;
String string = JOptionPane.showInputDialog(null,"How many stations are there?");
numOfStations = Integer.parseInt(string);
Stations[] stations = new Stations[numOfStations];
JOptionPane.showMessageDialog(null, stations.length);
return stations;
}
public static void main(String[] args){
Stations[] stations;
stations = createStationArray();
System.out.println("stations array value" + stations);
for(Stations station : stations)
{System.out.println("station variable value" + station);
int stationNum = 1;
double amountOfWaste;
station.setStationNum(stationNum);
String string = JOptionPane.showInputDialog(null,"What is this Station's waste amount?");
amountOfWaste = Double.parseDouble(string);
station.setWaste(amountOfWaste);
System.out.println("Station " + station.getStationNum() + " has a waste amount of " + station.getWaste());
}
}
}
我在变量“station”的for each循环中遇到问题。
它应该是数组列表中的当前对象。但是,我得到一个空指针异常。这里是控制台输出
stations array value[LStations;@28787c16
Exception in thread "main" java.lang.NullPointerException
at Calculation.main(Calculation.java:27)
station variable value null
erException
at Calculation.main(Calculation.java:27)
您创建了一个桩号数组,但没有填充它。因此,当您在数组上循环时,每个条目仍然为空。在调用方法之前,您需要实例化站点。在实例化Stations数组后,尝试在createStationArray()中添加以下内容:
for (int i = 0; i < numOfStations; i++)
stations[i] = new Stations();
for(int i=0;i