Changing Delimiter to Convert Military Time to Civilian Time

  • Thread starter Thread starter major_maths
  • Start date Start date
Join the discussion
Registration is free. Start your own thread to ask a follow-up.
3 replies · 2K views
major_maths
Messages
30
Reaction score
0
I'm trying to write a program that converts military time to civilian time (24-hour to the standard 12-hour) but I'm having trouble with changing the delimiter to ":". I've tried re-working the code every way I can think of and it still won't work properly.

Code:
import java.util.Scanner;
public class Program4
{
	public static void main(String[] args)
	{
		Scanner keyboard = new Scanner(System.in);		
		keyboard.useDelimiter(":");
		String theHour, theMin;

		System.out.println("Enter time in 24-hour notation.");
		theHour=keyboard.next();
		theMin=keyboard.next();
		
		System.out.println("The time is "+theHour+":"+theMin);
	}
}
 
Physics news on Phys.org
How are you entering the military time? Say, if it's 2 PM, are you entering 14:00 or 1400?
If you are entering it as 14:00, I would suggest using an int to store your values rather than a string,
then use nextInt instead of next.
 
Last edited:
I'm entering it like 14:00. I tried changing the variables to integers and used nextInt, but the program waits for me to do something else after that. I tried entering 14:00 again after that just to try something and got an InputMismatchException, if that helps.
 
It looks like the delimiter is not catching the whitespace at the end of the string that you entered. You need to delimit two things: the : and the whitespace character \\s by using a regular expression.
 
Last edited: