有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

扫描器的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()


共 (5) 个答案

  1. # 1 楼答案

    。。。您是否定义了您的专用扫描仪阅读器? 扫描仪阅读器=新扫描仪(System.in)

  2. # 2 楼答案

    您需要根据要扫描的实例构建reader

    在您的情况下,这应该如下所示:

    Scanner reader = new Scanner(System.in);
    

    然后,在代码片段之后,应该将EchoClient实例拥有的reader设置为构建的Scanner

  3. # 3 楼答案

    据我所知,阅读器从未初始化过

  4. # 4 楼答案

    看起来,当您创建新的EchoReader c时,它没有设置reader属性-然后当您尝试c.reader时,会得到null,在调用nextInt()时导致NPE。仔细检查EchoReader构造函数是否设置了reader属性

  5. # 5 楼答案

    reader从未初始化,因此它仍然为空