Reputation: 95
I am using Scanner to get user input. If the user inputs a name, I add that to the ArrayList
. If the user does not enter a name then I want to throw an exception, but I want to continue the loop that gets the answer.
for(int i = 0; i < totalLanes; i++){
runArr.add(this.addRacer());
}
public static String addRacer() throws NullPointerException{
System.out.print("Enter a name for a racer: ");//Method uses try catch to catch a NullPointerException.
Scanner sc = new Scanner(System.in);
String rName = null;
try {
if(!sc.nextLine().isEmpty()){
rName = sc.nextLine();
}else{
throw new NullPointerException("name cannot be blank");
}
}
catch (NullPointerException e) {
System.out.println(e.toString());
System.out.print("Enter a name for a racer: ");
addRacer();
}
return rName;
}
Thanks in advance.
Upvotes: 0
Views: 3474
Reputation: 4586
The problem is that you read input twice.
I mean you have two calls of sc.nextLine()
method in your code.
Try this instead:
String rName = sc.nextLine();
try {
if(rName.isEmpty()){
throw new NullPointerException("Name cannot be blank.");
}
}
Upvotes: 1
Reputation: 1
Don't call addRacer() function in catch. And also remove the line i have marked.Use if else condition for recursion.
catch (NullPointerException e) {
System.out.println(e.toString());
System.out.print("Enter a name for a racer: ");//remove this
addRacer();//remove this
}
Upvotes: 0
Reputation: 59950
You can use a do{}while()
in your case, this can be better way :
Scanner sc = new Scanner(System.in);
String rName;
do {
System.out.print("Enter a name for a racer: ");
rName = sc.nextLine();
try {
if (rName.isEmpty()) {
//throw and exception
throw new NullPointerException("name cannot be blank");
}
} catch (NullPointerException e) {
//print the exception
System.out.println(e.getMessage());
}
} while (rName.isEmpty());
return rName;
So you can't break your loop until the value in not empty.
Upvotes: 0
Reputation: 6780
You shouldn't throw an exception for that. Just use a while loop:
String rName = sc.nextLine();
while (rName.isEmpty()) {
System.out.println("Name can't be blank. Try again.");
rName = sc.nextLine();
}
return rName;
After that loop you are guaranteed to have a non-empty name in your variable, and you can use that name to add a new racer. You do not need recursion.
Upvotes: 0