该程序应允许用户输入每个月的跌落值,然后输出跌落和最干燥季节的平均值。它正在编译,但问题是我无法将数据输入数组。它允许我输入第一个数组元素的值,然后告诉我有一个错误:
Enter precipitation for each month:
Month #01 = 10
Exception in thread "main" java.lang.NullPointerException
at Seasons.In(Seasons.java:16)
at Seasons.main(Seasons.java:41)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Process finished with exit code 1
以下是代码:
import java.util.Scanner;
import java.util.ArrayList;
public class Seasons {
private ArrayList<Integer> monthList;
private int winter,spring,summer,autumn;
public void In(){
Scanner in = new Scanner(System.in);
System.out.println("Enter precipitation for each month: ");
for(int i=0;i<12;i++){
System.out.print("Month #"+i+1+" = ");
int a=in.nextInt();
monthList.add(i, a);
}
}
public int Calculate(){
int Sum = 0;
for(int element:monthList){
Sum+=element;
}
winter = monthList.get(11) + monthList.get(0) + monthList.get(1);
spring = monthList.get(2) + monthList.get(3) + monthList.get(4);
summer = monthList.get(5) + monthList.get(6)+ monthList.get(7);
autumn = monthList.get(8) + monthList.get(9) + monthList.get(10);
return Sum;
}
public void Out(int Result){
System.out.println("Average precipitation for this year is "+ Result/12);
if(winter<spring && winter<summer && winter<autumn) System.out.println("Winter was the driest season - "+winter);
else if(spring<summer && spring<autumn) System.out.println("Spring was the driest season - "+spring);
else if(autumn<summer) System.out.println("Autumn was the driest season - "+autumn);
else System.out.println("Summer was the driest season - "+summer);
}
public static void main(String[] args){
Seasons Precipitation = new Seasons();
Precipitation.In();
Precipitation.Out(Precipitation.Calculate());
}
}
感谢任何帮助。
UPD。:感谢您注意到我的无意识错误,现在它正常运作!
答案 0 :(得分:2)
用
private ArrayList<Integer> monthList;
目前您的列表为空(对象的默认值),当您执行monthList.add();
表示null.add()
为您提供Null Pointer
。将其更改为
private ArrayList<Integer> monthList=new ArrayList<Integer>();
答案 1 :(得分:1)
初始化ArrayList:
ArrayList<Integer> monthList =new ArrayList<Integer>();
答案 2 :(得分:0)
您的数组列表未初始化
private ArrayList<Integer> monthList;
应改为
private ArrayList<Integer> monthList = new ArrayList<>();
答案 3 :(得分:0)
你在这里
您没有初始化ArrayList。这就是全部
public static void main(String[] args) {
Seasons Precipitation = new Seasons();
Precipitation.monthList = new ArrayList<Integer>();//INITIALISE
Precipitation.In();
Precipitation.Out(Precipitation.Calculate());
}
如果有效,请将其标记为已接受。