[英]null pointer exception in dr.java
我正在尝试编写一个程序,在该程序中我需要输入一定数量的天数和起始温度。 在整天内,温度都会以某种方式变化。 然后打印最后一天的温度。 我的教授说要使用类TempPattern,字段num_days和first_day_temp以及构造函数和finalTemp方法。 这是我所拥有的:
public class TempPattern{
int num_of_days = 0;
int temp_first_day = 0;
public void TempPattern(int temp, int days){
days = num_of_days;
temp = temp_first_day;
}
public int num_of_days(int days){
return days;
}
public int temp_first_day(int temp){
return temp;
}
}
public void finalDayTemp(int days, int temp){
int half = days / 2;
int newtemp = temp + 2;
for (int current_day = 1; current_day <= half; current_day++){
newtemp = newtemp - 2;
}
for (int current_day = half + 1; current_day <= days; current_day++){
newtemp++;
}
System.out.println("Temperature on final day would be " + newtemp);
}
public void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int days;
int temp;
System.out.print("number of days: ");
days = keyboard.nextInt();
System.out.print("temperature of first day: ");
temp = keyboard.nextInt();
finalDayTemp(days,temp);
}
它可以编译,但是会出现该错误。
java.lang.NullPointerException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:267)
我认为某些东西是空值,但我真的不知道该如何解决。 我也认为我没有正确地完成整个构造函数和字段的工作,因此请随时提供任何帮助/建议,我对此表示赞赏。 我会清除所有没有意义的内容。 提前TY。
这里有一些越野车,需要更改:
找到以下修改后的代码:
import java.util.Scanner;
public class HWfive{
public static void findFinalDayTemperature(int days, int temp){
int half = days / 2;
int newtemp = temp + 2;
for (int current_day = 1; current_day <= half; current_day++){
newtemp = newtemp - 2;
}
for (int current_day = half + 1; current_day <= days; current_day++){
newtemp++;
}
System.out.println("Temperature on final day would be " + newtemp);
}
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int days;
int temp;
System.out.print("number of days: ");
days = keyboard.nextInt();
System.out.print("temperature of first day: ");
temp = keyboard.nextInt();
findFinalDayTemperature(days,temp);
}
class TemperaturePattern{
int num_of_days = 0;
int temp_first_day = 0;
public void TemperaturePattern(int temp, int days){
days = num_of_days;
temp = temp_first_day;
}
public int num_of_days(int days){
return days;
}
public int temp_first_day(int temp){
return temp;
}
}
}
静态方法的说明:加载类时会创建一个static
方法或变量。 仅当将类实例化为对象时(例如,使用new运算符),才会创建未声明为static
的方法或变量。
此外,虽然编制,并在开始执行的Java虚拟机不创建类的实例,而它只是加载main()
方法中, main()
方法必须与声明static
修改,以便尽快类加载后, main()
方法可用。
这些变量,哪些是外部的类的方法main()
不具有的方法static
修饰符不能使用,直到类的实例已经为中的对象创建main()
方法,所以你的情况方法'findFinalDayTemperature()'必须是静态的,才能由'main()'方法调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.