Quote
"What comes 13 hours after 4 o'clock? Create an ElapsedTimeCalculator application that prompts the user for a starting hour, whether it is am or pm, and the number of elapsed hours. The application then displays the time after that many hours have passed." (Guide to Programming in Java, Java 2 platform standard edition 5)
Application output should look similar to:
Enter the starting hour: 7
Enter am or pm: pm
Enter the number of elapsed hours: 10
The time is: 5:00 am
Application output should look similar to:
Enter the starting hour: 7
Enter am or pm: pm
Enter the number of elapsed hours: 10
The time is: 5:00 am
I have found what seems to be a decent solution, but I'm pretty sure it could be done in less characters even though I haven't been able to find a way that works all the time. Any one else have any advice or tips that would make my future programs less bulky and more easy to read?
//elena
import java.util.*;
public class ex11
{
public static void main (String args [])
{
Scanner input = new Scanner (System.in);
String Grr;
int time;
int elapsed = 0;
final String AfterNoon = "pm";
final String Morning = "am";
System.out.print ("Enter am or pm: ");
Grr = input.nextLine();
System.out.print ("Enter the starting hour: ");
time = input.nextInt ();
if (time <= 12)
{System.out.print ("Enter the number of elapsed hours: ");
elapsed = input.nextInt ();}
else
{System.out.println ("I don't know how to use that time keeping system!");}
//if its the afternoon it will change it to the 24 hour format
if (Grr.equalsIgnoreCase(AfterNoon))
{
time = time + 12;
time = time + elapsed;
if (time > 24)
{Grr = "am";
time = time - 24;}
else
{time = time - 12;
Grr = "pm";}
System.out.println ("The time is: " + time + ":00 " + Grr);
}
else if (Grr.equalsIgnoreCase(Morning))
{time = time + elapsed;
if (time > 11)
{Grr = "pm";
time = time - 12;}
System.out.println ("The time is: " + time + ":00 " + Grr);}
else
System.out.println ("You error-ed someplace, please read more carefully.");
}}


Sign In
Create Account


Back to top









