我使用的是 JDK 1.7, 我正在检查所有输入条件的代码。 如果用户未在字符串中输入任何值,则会抛出 NullPointerException。 即使用户没有输入任何值,是否有办法防止引发 NullPointerException?
我尝试了 try catch block 来捕获异常
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 空
预期输出- 5 (空字符串值->“”但没有抛出异常消息)
最佳答案
Java 8
int length = Optional.ofNullable(str).orElse("").length();
Java 7
int length = str == null ? 0 : str.length();
Java 7 + Apache Commons
int length = StringUtils.length(str);
使用扫描仪
使用Scanner
而不是BufferedReader
; scane.nextLine()
返回非 null
字符串。
public static void main(String... args) {
try (Scanner s = new Scanner(System.in)) {
System.out.println(s.nextInt());
s.nextLine();
String str = s.nextLine();
if (str.length() >= 1 && str.length() <= 15)
System.out.println(str);
}
}
关于java - 避免用户输入出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54270769/