[JAVA] Help with my code / Assignment

hello there,

so, i have an assignment, which asks to take the current time and ask for user input of hours and minutes and add it to the current time and display it as “future time is : XX:XX”. so far ive managed to slove most of it but when i enter more than 0 to 23 hour or more than 60 mins theres an error which i presume to be a logic error… :frowning: any ideas as to the correct formatting?

import java.time.LocalTime;
import java.util.Scanner ;

public class FutureTime 
{
	public static void main (String[] args)
	{
		//gets the current time, and stores as a LocalTime object called myTime
		LocalTime myTime = LocalTime.now();
		Scanner sc = new Scanner(System.in);
		
	     
		System.out.println("Ready to calculate a future time?");
	     
		//extracts hour and minute as ints from our LocalTime object
		int hour = myTime.getHour();
		int minute = myTime.getMinute();
	      
	     //  prints the current time and promts for user input  
		LocalTime justHoursAndMinutes = LocalTime.of(hour, minute); //uses ints from earlier
		System.out.println("Current time is: " + justHoursAndMinutes);
		System.out.println("Enter a positive number of hours and minutes, separated by a space: ");
		
		int newHours = sc.nextInt() + hour;
		int newMins = sc.nextInt() + minute ;
		LocalTime futureHoursAndMins = LocalTime.of(newHours , newMins);
		System.out.println("Future time is: " + futureHoursAndMins);
		//System.out.println("Future time is: " + newHours + ":" + newMins); IGNORE THIS
	     
		sc.close();
	}
}

You’re using LocalTime.of which creates a LocalTime based off the values you give it. anything more than 23 hours and 59 minutes isnt a time, e.g. 24:01 isnt a thing.

you need to take care of values that will push the time past the current day.

You should look at a slightly different way of doing it

https://docs.oracle.com/javase/8/docs/api/java/time/LocalTime.html

ISO 8601.

Please use that.

^This.

At the very least, you should be doing some error checking on the user input and ensure thst you handle things at that time.

convert to ms, add the two values(in ms) e.g now+input convert back to a date format.
so fx.
if you’re adding 3 hours 5 min.
it would become (3(60601000)+ (5(60*1000))+(millisecondsSince1970/now).
Then just convert back to a regular date stamp using that value.
more then likely there is a method for converting to ms, and back again to date object.
Its beena while since i worked with dates in Java so i forgot which methods exactly are available.

basically this is your cardinal sin, since you’re telling the date api, to calculate fx. 23+5 hours, or 45+20 minutes, which does not exist.

You need to do:

newHours %= 24;
newMins %= 60;

to get rid of the overflow.

1 Like

Bevor that add newHours = newHours + (int) (newMins/60);