问题遇到的现象和发生背景
问题:我输入 true 和 5之后报错Cannot invoke "dianti.set(boolean, int)" because "this.a" is null
这是什么原因我要怎么改?
题目:5.编写一个程序,模拟电梯得功能。功能接口包括电梯上行按钮、下行按钮、楼层选择与电梯在行驶过程中得楼层显示。
(1) 由用户选择按上行按钮还就是下行按钮,选择操作后再由用户输入要进入得楼层,进而电梯开始运行,显示所到得每一楼层层数.
(2) 如果就是上行,则选择输入得楼层号不能比当前楼层号小,否则应给出不合法提示。
(3) 如果就是下行,则选择输入得楼层号不能比当前楼层号大,否则应给出不合法提示。
(4) 电梯一旦开始运作就会始终运行,直到窗口关闭。
(5) 电梯在经过不同楼层时,最好每个楼层得显示之间能有延迟,最终停靠得楼层得输出形式能更加醒目。如果可以,在电梯最初开始运行时,能在电梯由内部显示当前日期。
用代码块功能插入代码,请勿粘贴截图
import java.util.*;
public class sadfaf {
public static void main(String[] args) {
while (true){
System.out.println("请输入上行true下行false");
Scanner x=new Scanner(System.in);
boolean l =x.nextBoolean();
System.out.println("请输入你想去的楼层");
Scanner y=new Scanner(System.in);
int m =x.nextInt();
user5 i=new user5(l,m);
i.zuodianti(l,m);
}
}
}
public class dianti {
int louceng=1;
boolean shangxia; //上1下0
void dianti1(int louceng){
this.louceng=louceng;
}
public void set(boolean x,int y){
this.shangxia=x;
if(x){
if(y>louceng){
for(int i=louceng+1;i<y+1;i++){
System.out.println("当前楼层为"+i);
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
dianti1(i);
}
}
else
System.out.println("输入错误");
}
if(!x){
if(y<louceng){
for(int i=louceng-1;i>y-1;i--){
System.out.println("当前楼层为"+i);
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
else
System.out.println("输入错误");
}
}
void show(){
System.out.println("当前楼层为"+louceng);
}
}
public class user5 {
boolean x;
int y;
dianti a;
public user5(boolean x,int y){
this.x=x;
this.y=y;
}
void zuodianti(boolean x,int y){
a.set(x,y);
}
}
运行结果及报错内容
请输入上行true下行false
true
请输入你想去的楼层
5
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "dianti.set(boolean, int)" because "this.a" is null
at user5.zuodianti(user5.java:10)
at sadfaf.main(sadfaf.java:32)
我想要达到的结果
程序正常运行