避免来自用户输入的 NullPointerException

我正在使用 JDK 1.7,我正在检查所有输入条件的代码。如果用户没有在字符串中输入任何值,那么它会抛出 NullPointerException。即使用户没有输入任何值,有没有办法防止导致 NullPointerException?


我尝试尝试捕获块来捕获异常


import java.util.*;

import java.io.BufferedReader;

import java.io.InputStreamReader;

class TestClass {

   public static void main(String args[]) throws Exception {


    Scanner s = new Scanner(System.in);    

    int i=s.nextInt();

    System.out.println(i);


    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    String str = br.readLine();

    try{

        int length=str.length();  //NullPointerException here


        if(length>=1 && length<=15)

        {

            System.out.println(str);

        }

    }

    catch(NullPointerException e)

    {

        System.out.println("Must enter a string");

    }

   }

}

样本输入 - 5 null


预期输出- 5(空字符串值->“”但没有抛出异常消息)


阿晨1998
浏览 148回答 3
3回答

心有法竹

爪哇 8int length = Optional.ofNullable(str).orElse("").length();爪哇 7int length = str == null ? 0 : str.length();Java 7 + Apache Commonsint length = StringUtils.length(str);采用Scanner使用Scanner代替BufferedReader; scane.nextLine()返回不是null字符串。public static void main(String... args) {&nbsp; &nbsp; try (Scanner s = new Scanner(System.in)) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(s.nextInt());&nbsp; &nbsp; &nbsp; &nbsp; s.nextLine();&nbsp; &nbsp; &nbsp; &nbsp; String str = s.nextLine();&nbsp; &nbsp; &nbsp; &nbsp; if (str.length() >= 1 && str.length() <= 15)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(str);&nbsp; &nbsp; }}

慕婉清6462132

1) 阅读文档 - 请注意 BufferedReader.readline 在明确定义的情况下可以合法地返回 null。2)编写可以处理可能的空返回的代码。

弑天下

import java.util.*;import java.io.BufferedReader;import java.io.InputStreamReader;class TestClass {&nbsp; &nbsp;public static void main(String args[]) throws Exception {&nbsp; &nbsp; Scanner s = new Scanner(System.in);&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; int i=s.nextInt();&nbsp; &nbsp; System.out.println(i);&nbsp; &nbsp; BufferedReader br = new BufferedReader(new InputStreamReader(System.in));&nbsp; &nbsp; String str = br.readLine();&nbsp; &nbsp; &nbsp; &nbsp; if(str!=null && str.length() >=1 && str.length()<=15)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(str);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp;}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java