Reputation: 29
I am using JDK 1.7, I am checking the code for all conditions of input. if user does not enter any value in the String then it throws a NullPointerException. Is there a way to prevent causing NullPointerException even if the user does not enter any value?
i tried try catch block to catch exception
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");
}
}
}
sample input- 5 null
Expected Output- 5 (Empty string value-> "" but no exception thrown message)
Upvotes: 2
Views: 510
Reputation: 18245
int length = Optional.ofNullable(str).orElse("").length();
int length = str == null ? 0 : str.length();
int length = StringUtils.length(str);
Scanner
Use Scanner
instead of BufferedReader
; scane.nextLine()
returns not null
string.
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);
}
}
Upvotes: 3
Reputation:
1) Read the documentation - note that BufferedReader.readline can legitimately return null under well-defined circumstances.
2) Write code that can handle the possible null return.
Upvotes: 0
Reputation: 299
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();
if(str!=null && str.length() >=1 && str.length()<=15)
{
System.out.println(str);
}
}
}
}
Upvotes: 0
Reputation: 1343
Instead of try/catch you could check if str is not null before you call str.length()
Scanner s = new Scanner(System.in);
String str = s.nextLine();
if (str != null && str.length() <= 15) {
System.out.println(str);
} else {
System.out.println("Must enter a string");
}
Upvotes: 0