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:7 | ISBN:9780136091813 | Edition: 2

Question

Add the following method to the TimeSpan class:
public void scale(int factor)
Scales this time span by the given factor. For example, 1 hour and 45 minutes scaled by 2 equals 3 hours and 30 minutes.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

// package classes;

public class TimeSpan {

    private int hours;
    private int minutes;

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

    // this methods thorws an error if invalid hours and miutes 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;
    }




// multiple the time with factor
    public void scale(int factor) {
        // this makes sure it throws illegal argument exception
        if(factor<0)
           throw new IllegalArgumentException();
        
        // calculate the minutes and multiply with factor
        this.minutes = (((this.hours*60+this.minutes))*factor)%60;
        // calculate by dividing with 60 you will get total hours
        this.hours  = (((this.hours*60+this.minutes))*factor)/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(2, 6);
        
        TimeSpan elapsed2 = new TimeSpan(2, 56);

        System.out.println("elapsed time before scale: " + elapsed);
        
        elapsed.scale(2);
        

        System.out.println("elapsed time after scalling with factor: " + elapsed);

    }

}



Output:


elapsed time before scale: 2h 6m
elapsed time after scalling with factor: 4h 12m


0 0

Discussions

Post the discussion to improve the above solution.