Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package MyClock;
- public class Clocker {
- private int hours, minutes;
- private final int max_hours = 24, max_minutes = 60, min_value = 0;
- private static int format = 24;//default format
- public Clocker(int hours, int minutes) {
- this.setHours(hours);
- this.setMinutes(minutes);
- } //main constructor
- public Clocker(Clocker object) {
- this.hours = object.getHours();
- this.minutes = object.getMinutes();
- } // cloning constructor
- public Clocker() {
- this(0, 0);
- } //constructor for cases we build an empty object
- public boolean setHours(int hours) {
- if (hours <= min_value || hours > max_hours) {
- this.hours = min_value;
- return false;
- } else {
- this.hours = hours;
- return true;
- }
- }
- public boolean setMinutes(int minutes) {
- if (minutes <= min_value || minutes > max_minutes) {
- this.minutes = min_value;
- return false;
- } else {
- this.minutes = minutes;
- return true;
- }
- }
- public int getHours() {
- return hours;
- }
- public int getMinutes() {
- return minutes;
- }
- /***
- *
- * getFormat and setFormat will be static because of the parameter "format" is static
- */
- public static boolean setFormat(int format) {
- if (format != 12 && format != 24) {
- Clocker.format = 0;
- return false;
- }
- Clocker.format = format;
- return true;
- }
- public static String getFormat() {
- return format == 12 ? "am:pm format" : "24 hours format";
- }
- @Override
- public String toString() {
- if (format == 12) {
- return (hours < 10 ? "0" : "") + (hours == 12 ? hours : hours % 12) + ":" + (minutes < 10 ? "0" : "") + minutes + (hours < 12 ? "am" : "pm"); //in case of am:pm format it will write am or pm in the end of the string
- }else {
- return (hours < 10 ? "0" : "") + hours + ":" +(minutes < 10 ? "0" : "")+ minutes; // if an hour is until 10 it will write 0 at
- }
- }
- }
- =======================================================================================================================================
- import java.util.*;
- import MyClock.*;
- public class objectsClassesFirstLesson {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- System.out.println("Plese write 12 for am:pm format or 24 for 24 format:");
- //we can use format before we do any object of class
- Clocker.setFormat(sc.nextInt());
- // new object of class
- Clocker shaon = new Clocker(12, 30);
- // see it prints right
- System.out.println(shaon + " " + shaon.getFormat());
- // using cloner constructor
- Clocker chas = new Clocker(shaon);
- // change the time of first object
- shaon.setHours(0);
- shaon.setMinutes(56);
- // checking cloner constructor works
- System.out.println(shaon + " " + shaon.getFormat());
- System.out.println(chas + " " + chas.getFormat());
- }
- }
Add Comment
Please, Sign In to add comment