Friday, November 6, 2015

// // Leave a Comment

Program To Find Number Of Years

The program below is the answer to Liang's Introduction to Java Programming (9th Edition) Chapter 2 Exercise 2.7.

Question: (Find the number of years) Write a program that prompts the user to enter the minutes (e.g., 1 billion), and displays the number of years and days for the minutes. For simplicity, assume a year has 365 days.

/**
 *
 * @Author: Aghatise Osazuwa
 * Website: www.cscprogrammingtutorials.com
 *
 * Exercise 2.7 - Find The Number Of Years
 *
 */ 

import javax.swing.JOptionPane;

public class FindNumberOfYears {
    public static void main (String [] args) {
        System.out.println("This Program Displays The Number Of Years And Days "
                + "In The Value Of Minutes Entered.\n");
        String number = JOptionPane.showInputDialog(null, "Enter the number of minutes:", 
                "Input Dialog", JOptionPane.QUESTION_MESSAGE);
        int minutes = Integer.parseInt(number);
        int hours = minutes / 60;
        int days = hours / 24;
        int years = days / 365;
        int remainingDays = days % 365;
        
        String message = minutes + " minutes is approximately " + years + 
                " years and " + remainingDays + " days.\n";

        JOptionPane.showMessageDialog(null, message, "Answer", JOptionPane.INFORMATION_MESSAGE);
    }
}

The above program was done using Java's GUI. The same code without using GUI is written below:

import java.util.Scanner;

public class FindNumberOfYears {
    public static void main (String [] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("This Program Displays The Number Of Years And Days "
                + "In The Value Of Minutes Entered.\n");
        System.out.println("Enter the number of minutes: );
        int minutes = input.nextInt();
        int hours = minutes / 60;
        int days = hours / 24;
        int years = days / 365;
        int remainingDays = days % 365;
        
        System.out.printf (minutes + " minutes is approximately " + years + 
                " years and " + remainingDays + " days.\n");
    }
}


Click here to see other solutions to Introduction to Java Programming.

0 comments:

Post a Comment


DISCLAIMER: Opinions expressed in comments are those of the comment writers alone and does not reflect or represent the views of the post author. We reserve the right to delete any post deemed inappropriate or offensive and/or spammy. Please do not use abusive words/hate speech.

I Appreciate your valuable Feedback. So, Please DO NOT SPAM - Spam comments will be deleted immediately.

Don't use brand name in name field and you're not allowed to use links in comments unless it's necessary. Such comments will be removed immediately.

Thanks.