SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Classes
Exercise:
Exercises
Question:5 | ISBN:9780136091813 | Edition: 2

Question

Add the following method to the TimeSpan class:
public void add(TimeSpan span)
Adds the given amount of time to this time span.

 

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer



// package classes;

public class TimeSpan {

	private int hours;
	private int minutes;

	// Constructor to pass hours and minutes
	public TimeSpan(int hours, int minutes) {
		this.hours = 0;
		this.minutes = 0;
		add(hours, minutes);
	}

	// this methods throws an error if invalid hours and minutes passes into the
	// argument
	public void add(int hours, int minutes) {
		if (hours < 0 || minutes < 0) {
			throw new IllegalArgumentException();
		}

		this.hours += hours;
		this.minutes += minutes;

		// converts each 60 minutes into one hour
		this.hours += this.minutes / 60;
		this.minutes = this.minutes % 60;
	}

	// returns a String for this time span, such as "6h 15m"
	public String toString() {
		return hours + "h " + minutes + "m";
	}

	
		
	public static void main(String[] args) {

		TimeSpan elapsed = new TimeSpan(3, 56);
		

		System.out.println("elapsed time before adding: " + elapsed);
		
		elapsed.add(2, 78);

		System.out.println("elapsed time after adding: " + elapsed);

	}

}
Output:

elapsed time before adding: 3h 56m
elapsed time after adding: 7h 14m

 

0 0

Discussions

Post the discussion to improve the above solution.