扫描器的java问题
我正在编写一个java程序,它将int输入作为用户的一个选项。根据输入,程序将转到不同的方法。但当我运行代码时,它会给出以下错误
Exception in thread "main" java.lang.NullPointerException
at lab1.EchoClient.main(EchoClient.java:25)
我代码的一部分
private Scanner reader;
public static void main(String[] args){
EchoClient c = new EchoClient();
int option;
System.out.println("Welcome");
System.out.println("Select one of the following options:");
System.out.println("1 - Iterative Server");
System.out.println("2 - Concurrent Server");
System.out.println("3 - Exit");
option = c.reader.nextInt(); // Line No 25
switch(option){
case 1:
c.iterative();//calls the iterative method
break;
case 2:
//some method
break;
case 3:
System.out.println ("bye bye");
break;
}//end of switch()
}//end of main()
public void iterative(){
String address;
String ip="";
try{
System.out.println ("Please enter your correct ip address");
BufferedReader getip= new BufferedReader (newInputStreamReader(System.in));
ip=getip.readLine();
}
catch (IOException error){
System.err.println("Error occured");
}
第25行是:option=c.reader。nextInt()
# 1 楼答案
。。。您是否定义了您的专用扫描仪阅读器? 扫描仪阅读器=新扫描仪(System.in)
# 2 楼答案
您需要根据要扫描的实例构建reader
在您的情况下,这应该如下所示:
然后,在代码片段之后,应该将
EchoClient
实例拥有的reader
设置为构建的Scanner
# 3 楼答案
据我所知,阅读器从未初始化过
# 4 楼答案
看起来,当您创建新的
EchoReader c
时,它没有设置reader
属性-然后当您尝试c.reader
时,会得到null
,在调用nextInt()
时导致NPE。仔细检查EchoReader
构造函数是否设置了reader
属性# 5 楼答案
reader
从未初始化,因此它仍然为空