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
JavaBot
JavaBot•2w ago
⌛ This post has been reserved for your question.
Hey @TomiWebPro! Please use /close or the Close 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.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
JavaBot
JavaBot•2w ago
Please format your code to make it more readable. For java, it should look like this:
​`​`​`​java
public void foo() {

}
​`​`​`​
​`​`​`​java
public void foo() {

}
​`​`​`​
dan1st
dan1st•2w ago
Don't create new Scanners in every iteration instead, create one Scanner and reuse it
JavaBot
JavaBot•2w ago
💤 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.
Want results from more Discord servers?
Add your server