Error Handling with try and while
Hi guys 'm a total newbee, when I call this function it just prints "Input cannot be empty. Please enter a valid string." forever and disallow me to enter anything after first attempt, How do I correctly incorporate error handling here?
"""
public static String inputString(String toPrint) {
System.out.print(toPrint);
boolean notExitWhile = true;
String inputString = "";
while (true) {
try {
Scanner scanner = new Scanner(System.in);
inputString = scanner.nextLine();
if (inputString.trim().isEmpty()) {
System.out.println("Input cannot be empty. Please enter a valid string.");
}else{
break;
}
} catch (Exception e) {
System.out.println("Wrong input! String expected.");
}
}
return inputString;
}
""
4 Replies
⌛
This post has been reserved for your question.
Hey @TomiWebPro! Please useTIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here./close
or theClose Post
button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically marked as dormant after 300 minutes of inactivity.
Please format your code to make it more readable. For java, it should look like this:
Don't create new
Scanner
s in every iteration
instead, create one Scanner
and reuse it💤
Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived.
If your question was not answered yet, feel free to re-open this post or create a new one.
In case your post is not getting any attention, you can try to use /help ping
.
Warning: abusing this will result in moderative actions taken against you.