I am trying to take in a string formatted as HH:mm (24 hr format) and then subtract 45 minutes from that given time to provide the user a new time. Here is the code I have completed so far but I keep getting an Incomplete type error. Am I using the minusMinutes() incorrectly?
Edit adding error message: "Incompatible types found: 'java.time.LocalDateTime', required: 'java.lang.String': 52'
public static boolean validateTime(String timeStr)
{
//Regular expression logic to validate correct format:
// ( = start of group, [01]?[0-9] time can start with 0-9,1-9, 00-09,10-19
// | = or, 2[0-5] represents start time with 20-23, ) = end group
//
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: ");
timeIn = myScanner.nextLine();
}
System.out.println("Current Time is: " timeIn);
//String[] arrOfStr = timeIn.split("\\:");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
LocalDateTime datetime = LocalDateTime.parse(timeIn,formatter);
String updatedTime = datetime.minusMinutes(45);
System.out.println("New time to wake up: " updatedTime);
CodePudding user response:
You need to add a toString()
to stringify the time object. Also, as you're only reading a time, use LocalTime
instead of LocalDateTime
Your last few lines would then look like:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
LocalTime datetime = LocalTime.parse(timeIn, formatter);
String updatedTime = datetime.minusMinutes(45).toString();
System.out.println("New time to wake up: " updatedTime);