I am relatively new to programming and Java in particular. I am working on a project that requires the user to enter the time in 24 hour format. I used regular expressions to validate the input, but anytime there is invalid input passed in the while loop will not break its loop.
enter image description here
Is this a problem with my validateTime function or the structure of my while loop?
import java.util.Scanner;
import java.util.regex.*;
public class Project1 {
public static boolean validateTime(String timeStr)
{
//Regular expression to validate correct format
String regex = "([01]?[0-9]|2[0-3]):[0-5][0-9]";
Pattern p = Pattern.compile(regex);
//if time empty return false
if (timeStr == null)
{
return false;
}
//matcher method attempts to find match between given time and regex
Matcher m = p.matcher(timeStr);
//if given time and Regular expression matches,return true.
return m.matches();
}
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println("Enter time in 24 hr format (HH:mm): ");
String timeIn = myScanner.nextLine(); // read user input
while(!validateTime(timeIn))
{
System.out.println("Please enter valid time: ");
myScanner.nextLine();
}
}
}
>Solution :
The while loop is based on the boolean validateTime(timeIn), so if you want to change the boolean, you have to change the timeIn variable in your while loop. However, this never occurs. This is because the input you have taken from the Scanner is never given to the variable timeIn to update its value. Please change the line
myScanner.nextLine()
to
timeIn = myScanner.nextLine();