TomiWebPro
JCHJava Community | Help. Code. Learn.
•Created by TomiWebPro on 11/13/2024 in #java-help
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;
}
""
7 replies