Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: Fun little problem I made for myself, and now I need help trying to solve it.

  1. #1
    Junior Member
    Join Date
    Oct 2012
    Posts
    9
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Fun little problem I made for myself, and now I need help trying to solve it.

    I just finished a tutorial on youtube on how to set a time then make it display in military format. I followed along and did the actual tutorial just fine. But I decided to give myself a little problem/project to solve and since I'm a beginner I'm stumped and stuck. I feel so close but I can't get anything to work. I do feel like I've gotten a little bit better understanding of how int variables and strings work though.
    Anyways here is my problem.

    I am trying to loop this method to keep going until a certain condition is true. I want it to stop only when it randomly displays a set time, let's say 07:07:07.

    class apples{
     
    	public static void main(String[] args) {
    		tuna tunaObject = new tuna();
     
    		{
    		tunaObject.setTime((int)((Math.random()*23)+1), (int)((Math.random()*59+1)), (int)((Math.random()*59)+1));
    		System.out.println(tunaObject.toMilitary());
    		}
     
    	}
    }

    public class tuna {
     
    	private int hour;
    	private int minute;
    	private int second;
     
    	public void setTime(int h, int m, int s){
    		hour = ((h>=0 && h<24) ? h : 0);
    		minute= ((m>=0 && m<60) ? m : 0);
    		second = ((s>=0 && s<60)? s : 0);
    	}
     
     
    	public String toMilitary(){
    		return String.format("%02d:%02d:%02d", hour, minute, second);
    	}
     
     
    }

    I've tried to stick in for and while loops, through the ints int a new variable, turn them into a string, and fumbled with booleans. I also tried to make a get method but I kind of got lost in doing that too.
    Now I just have a headache and I'm just doing this for fun so I think it's okay for me to ask for some help.

    Thanks!


  2. #2
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: Fun little problem I made for myself, and now I need help trying to solve it.

    Quote Originally Posted by 0ffConstantly View Post
    ....I do feel like I've gotten a little bit better understanding of how int variables and strings work...
    Anyways here is my problem.

    I am trying to loop this method to keep going until a certain condition is true. I want it to stop only when it randomly displays a set time, let's say 07:07:07.
    So: You have a timer that has three int fields: hour, minute, and second. You have a method that takes three ints and uses them to set the "time" of the timer, as represented by its three int fields.

    So, here could be the next step:

    Create three public methods: One that returns the int value of the hour field, one returns the int value of the minute field, and, well, you get the idea.

    I mean, having the program create a String suitable for printing is a nice touch, but why the heck would you want your main program have to parse that string every stinkin' time it needed to see what the hour,minute,second timer values are? (There is a counter-argument that favors doing everything with Strings, but I'll leave that to experts who might want to chime in.) There are certainly other ways. Maybe "better" ways from some points of view. But I would like to build on what you started...

    Anyhow, with these three "getter" methods here's the plan for a test program:

    Obtain, somehow, three integer values that correspond to hours, minutes and seconds of an "alarm" time. Maybe have the user enter a String of form "hh:mm:ss" for the "alarm" time and parse the String. Or have the user enter three integers for hour, minute, and second of the "alarm" time. Or, for starters, just hard-code the integer values into the program.

    Now, first of all, I seriously recommend that you pick meaningful values for classes. I mean, my alarm clock might be named "Dopey" and I would be named "Grumpy," but for purposes of programming, I would call the class with the timer something like MilTimer or some such thing. Be creative. You can probably do better that, but, not "tuna" Please. (You will thank me later, when you leave your schooldays behind.)

    Anyhow, the class that I build to test the timer might go like this:
    class TestTime {
     
        public static void main(String[] args) {
            MilTimer timer = new MilTimer();
     
            // For now, just hard-code the alarm time.
            int alarmHours = 7;
            int alarmMinutes = 7;
            int alarmSeconds = 7;
     
            // I think it might be enlightening to see how many random
            // time calls it makes to arrive at the alarm time.  I'll keep count
            // with a variable creatively named "count."
            //
            int count = 0;
            //
            // Now, here's the loop that sets random times until it reaches
            // the alarm time:
            //
            while (/* Put boolean conditions that make the loop continue until hour, minute, second
                      values from the timer all match alarmHours, alarmMinutes and alarmSeconds */)
            {
                ++count;
                timer.setTime((int)((Math.random()*24)),  // Hours go from 0 through 23
                              (int)((Math.random()*60)),  // Minutes go from 0 through 59
                              (int)((Math.random()*60))); // Seconds go from 0 through 59
                //
                // Print out each one
                //
                System.out.printf("%10d: %s\n", count, timer.toMilitary());
            }
            //
            //  After it finally reaches the alarm time, print a summary.
            //
            System.out.printf("Number of random times to get to %s = %d\n", timer.toMilitary(), count);
     
        } // End of main method
    } // End of class definition


    A "typical" run might look like

    .
    . // A LOT of numbers
    .
    105266: 12:56:49
    105267: 15:40:58
    105268: 06:37:34
    105269: 19:33:38
    105270: 16:05:46
    105271: 07:07:07
    Number of random times to get to 07:07:07 = 105271


    After a few runs where you can see each and everything go scrolling off the screen, you will probably want to comment out the print statement inside the loop and just show the summary. Run it a few times. What kind of count values do you observe? Would it make any difference if you used a different alarm time?

    What if you made a big loop that ran the main part of this, say 1000 times and calculated the average count value. What would you expect the average count value to be? See how much fun you can have with a simple little program like this that even a beginner can conceive and implement? Man! What a rush! My creative juices are really flowing now!

    Anyhow...

    My approach was this: Even though I didn't like the name you gave the class, I like that your timer used separate integer variables for hours, minutes and seconds. I will build my program around those three integers.

    Some people would use a single integer that represents total seconds since 00:00:00, and would supply methods that would convert three integers (h, m, s) to total seconds and convert total seconds back to (h, m, s). Maybe I would have done it that way, or maybe I would have done it your way. The actual implementation of a "real" clock might favor one approach over the other, and you can experiment with different ways of doing things once you get your testbed in place.

    Now, maybe your approach would be different and maybe your implementation would be different, but one big thing about program design is to define and visualize what the output will be.

    This is where the Big Bucks are: Program design. Making decisions. Even though I showed some implementation details before I showed the output, my visualization of the functionality and of the specific output came before I wrote a single line of code. (Well, I started with your timer class and went from there. Lots of times that's what you do. Other times you start from scratch.)

    Anyhow, once program design is complete, if you "do it right," you can use your newly-learned knowledge of Java to create the program. The actual implementation will be a "snap."

    The only thing that remains TBD (To Be Done) in main() is to fill in the parentheses in the while(){} loop statement.

    You want to continue the loop as long as (hours don't match) OR (minutes don't match) OR (seconds don't match).

    Just use Java boolean expressions where "!=" (not equal) is used for the (don't match) conditions and "||" is used for the connective OR, OK?

    Cheers!

    Z
    Last edited by Zaphod_b; October 18th, 2012 at 05:32 PM.

  3. The Following User Says Thank You to Zaphod_b For This Useful Post:

    0ffConstantly (October 19th, 2012)

  4. #3
    Junior Member
    Join Date
    Oct 2012
    Posts
    9
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Fun little problem I made for myself, and now I need help trying to solve it.

    Yeah, the class names were just from the tutorial. I usually like to stay more organized. Anyways thank you! That really helped. I was struggling with how to get integer values to compare and how to compare. Once I got a vague idea of how to do it. I just typed it in and after a few syntax corrections from the IDE and it prompting me to make the int values Static I got it to work. I didn't make it as fancy as yours but here is the code of mine that I got to work just the way I wanted.

    class apples{
     
    	public static void main(String[] args) {
    		tuna tunaObject = new tuna();
     
    		 int alarmHours = 7;
    	        int alarmMinutes = 7;
    	        int alarmSeconds = 7;
     
    	        int counter = 0;
     
     
    	 while (alarmHours!=tuna.getHour() || alarmMinutes!=tuna.getMinute() || alarmSeconds!=tuna.getSecond()){
     
    		{
    			++counter;
    		tunaObject.setTime((int)((Math.random()*23)+1), (int)((Math.random()*59+1)), (int)((Math.random()*59)+1));
    		System.out.println(tunaObject.toMilitary());
    		}
    	}
    		System.out.println("it took "+ counter+ " tries");
    }
     
    }

    public class tuna {
     
    	public static int hour;
    	public static int minute;
    	public static int second;
     
    	public void setTime(int h, int m, int s){
    		hour = ((h>=0 && h<24) ? h : 0);
    		minute= ((m>=0 && m<60) ? m : 0);
    		second = ((s>=0 && s<60)? s : 0);
    	}
     
    	public static int getHour() {
    	       return hour;
    	    }
    	public static int getMinute() {
    	       return minute;
    	    }
    	public static int getSecond() {
    	       return second;
    	    }
     
    	public String toMilitary(){
    		return String.format("%02d:%02d:%02d", hour, minute, second);
    	}
     
     
    }

    I got
    ...
    22:56:54
    05:37:22
    08:28:40
    04:14:27
    22:11:26
    07:07:07
    it took 85992 tries

    Now that we've got that done. I feel a little bit accomplished. Haha, I'm still taking babysteps with this java thing. Anyways if anybody has any input on how to make this code more efficient? Or how they would have solved it. I'd love to see your code and read your explanation.
    Thanks guys!
    Last edited by 0ffConstantly; October 19th, 2012 at 04:49 PM.

Similar Threads

  1. Need help to solve this problem
    By ahanf in forum Object Oriented Programming
    Replies: 1
    Last Post: June 3rd, 2012, 05:00 AM
  2. need help to solve the problem
    By priyadaradi in forum Member Introductions
    Replies: 1
    Last Post: May 24th, 2012, 10:44 AM
  3. help me to solve my problem
    By miszIna in forum Object Oriented Programming
    Replies: 3
    Last Post: February 14th, 2011, 09:40 AM
  4. Plz solve the problem
    By rasheedmgs in forum JavaServer Pages: JSP & JSTL
    Replies: 1
    Last Post: October 14th, 2010, 11:59 AM
  5. Replies: 3
    Last Post: June 14th, 2009, 09:31 PM