【问题标题】:java.lang.NullPointerException form user inputjava.lang.NullPointerException 表单用户输入
【发布时间】:2015-10-11 17:12:07
【问题描述】:

大家好,我正在尝试创建一个循环,直到用户输入正确的字符选择。当我输入错误的选择时,我收到错误 java.lang.NullPointerException。这可能与我输入的方式有关,但如果我不需要,我不想改变它。选择是类的私有成员。

char wf() { 
    Scanner input = new Scanner(System.in); 
    System.out.println("What is your choice? (x/o)"); 
    choice = input.findInLine(".").charAt(0);

    while (choice != 'x' && choice != 'o') { 
        System.out.println("You must enter x or o!");
        choice = input.findInLine(".").charAt(0);
    }

    return choice; 
}//end wf

【问题讨论】:

  • findLineAt 是否返回 null?如果是这样,那就是问题所在,因为您之后立即致电charAt。如果findLineAtnull,您将无法调用方法,因为没有可调用方法的对象(而是有null),因此是NPE。
  • 既然很明显findLineAt 返回null 你只需要理解为什么。您可以通过阅读 JavaDoc 并调试此方法来做到这一点,看看那里发生了什么。

标签: java nullpointerexception java.lang.class


【解决方案1】:

改函数如下(我已经测试过这段代码):

char wf() { 
    Scanner input = new Scanner(System.in); 
    System.out.println("What is your choice? (x/o)"); 
    char choice = input.findInLine(".").charAt(0);

    while (choice != 'x' && choice != 'o') { 
        System.out.println("You must enter x or o!");
        choice = input.next().charAt(0);
    }

    return choice; 
}//end wf

【讨论】:

    【解决方案2】:

    检查 input.findInLine(".") 是否为空。如果您没有预期的输入,它将不会返回任何内容..

    【讨论】:

      【解决方案3】:

      如下修改你的代码

      char wf() { 
      Scanner input = new Scanner(System.in); 
      System.out.println("What is your choice? (x/o)"); 
      if(input.findInLine(".") !=null){
      choice = input.findInLine(".").charAt(0);
      while (choice != 'x' && choice != 'o') { 
          System.out.println("You must enter x or o!");
          choice = input.findInLine(".").charAt(0);
       }
      }
      return choice; 
      }//end wf
      

      【讨论】:

      • 你能解释为什么它应该工作,即使它没有?
      猜你喜欢
      • 2019-05-31
      • 2019-04-26
      • 1970-01-01
      • 2015-02-07
      • 2013-04-18
      • 1970-01-01
      • 2015-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多