For a program I'm writing, I need to read in a user-inputted time with the format HH:MM:SS AM (or PM). The program must exit when the user types "quit". I must use a delimiter to initialize the hours, minutes, seconds, and AM/PM variables from the user-inputted String.
In order to check that the user did not type "quit" I first read in the String and did a standard check using the equalsIgnoreCase("quit")
method. However, I need to be able to use a delimiter on the String if the "quit" check passes. Since my initial scanner is reading input from the System.in
stream, how would I use a delimiter on the String I have already read in without creating another Scanner object like this:
Scanner input = new Scanner(s).useDelimiter(":|\\s+");
?
My code is below:
import java.util.Scanner;
public class Delimiter
{
public static void main(String[] args)
{
int hours, minutes, seconds = 0;
String ampm, s = "";
Scanner scan = new Scanner(System.in);
while (true)
{
s = scan.nextLine(); //scans input
if (s.equalsIgnoreCase("quit")) //checks if input is "quit"
{
System.out.println("Exiting program.");
return; //exits method
}
else
{
Scanner input = new Scanner(s).useDelimiter(":|\\s+"); //This is what I want to avoid
hours = input.nextInt();
minutes = input.nextInt();
seconds = input.nextInt();
ampm = input.nextLine().trim();
}
System.out.println("Hours = " + hours);
System.out.println("Minutes = " + minutes);
System.out.println("Seconds = " + seconds);
System.out.println("Morning or Afternoon = " +ampm);
}
}
}