简体   繁体   中英

Java Code to convert seconds into minutes, hours and days

I am trying to create a Java code that asks the user to insert a number of seconds they would like to convert, how ever i can't get it to work. Can some one help?? Code Below ...................................

import javax.swing.*;

public class Week2Seconds {


    private static final int MINUTES_IN_AN_HOUR = 60;
    private static final int SECONDS_IN_A_MINUTE = 60;

    public static void main(String[] args) {

        JFrame frame = new JFrame("InputDialog");

        String seconds   = JOptionPane.showInputDialog(frame, "Enter Number Of Seconds to Convert");

    }

  private static String timeConversion(int seconds) {

        final int MINUTES_IN_AN_HOUR = 60;
        final int SECONDS_IN_A_MINUTE = 60;

        int minutes = seconds / SECONDS_IN_A_MINUTE;
        seconds -= minutes * SECONDS_IN_A_MINUTE;

        int hours = minutes / MINUTES_IN_AN_HOUR;
        minutes -= hours * MINUTES_IN_AN_HOUR;

        return hours + " hours " + minutes + " minutes " + seconds + " seconds";
    }
}

Many Thanks Vinnie

You have your seconds stored as a String , the computer doesnt know that the input is a number and heck it might not even be a number. You can use the static method Integer.parseInt to attempt to convert the string to an integer.

int numSeconds = Integer.parseInt(seconds)

This can throw a NumberFormatException if seconds is not a valid number.

Once you have the number as the correct type you can pass this to your method timeConversion(numSeconds);


As per your comment on why your program isnt exiting correctly because you created a JFrame , the JFrame will keep your program running until it is properly disposed of. Using the JFrame class is outside the scope of your question, however your program you dont need this frame at all, remove it. Pass null as the parentComponent for the showInputDialog method.

JOptionPane.showInputDialog(null, "Enter Number Of Seconds to Convert");


Some followup questions you might have could be:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM