Beginner Programmer: Timer

I'm pretty new to Java (or to any programming language for that matter), and I was wondering how to make a timer, and how hard it is to make one. In my programming class at school, all our programs were pretty small, and they only ran in the compiler in Dr. Java. Well I'm making a small game, and what I want is a System.out.println("!"); or something like that, and then a readLine(); where the user types what is printed (The exclamation mark). The goal I want requires some sort of timer, that counts to 2 seconds or something. When the timer is up, it will skip the Textbox that pops up, and display "You were too slow!", and if they type it quickly enough, the game prints "You beat the timer!", and continue with the game.
Basically:
System.out.println("!");
//Timer starts
in = br.readLine(); //'in' being a String to hold input, and 'br' being the BufferedReader. If timer runs out, skip the textbox, or just send 'in' the wring answer, continuing the game
//Timer stops
if (in.equals("!") && //Timer was less than 2 seconds) {
System.out.println("You did it!"); }
else {
System.out.println("You were too slow!");  }Is this possible? If so, can someone post the code for it, or explain how to make it? I REALLY want this to work!!!
Thanks in advanced!

Dr.Awesome wrote:
Ok, I ran the program and it works, but it won't stop when I press Ctrl+C, was that just an example or was it really supposed to stop? It wasn't actually suppose to stop if you press Ctrl+C. You would have to add some sort of key listener for that to happen. At this point, that's a probably a little too complex.
Also, just so I can fully understand this, what does .printf do? I've been taught .println and .print already. To me it looks like it has the same effect as .print...Printf basically prints a formatted string. By "formatted string" I mean that you can do things like left justification, right justification, show only 3 decimals, ect.. Just stick with print and println for now.
Next, I recognize the 'while' but we've only used it after a 'do'. Does it just repeat the timer.schedule?The while loop keeps the program (and more specifically the Java Virtual Machine) from exiting. It's kind of awkward example for a person new to java, since they would have to understand a little about Threads to see its purpose. If you don't know what threads are, then I'm not sure you should be trying to delve into the Timer class.
A 'while' loop is pretty much the same thing as a do-while loop ( link ) but in the case of the do-while loop you necessarily do at least one iteration before checking the condition in the while statement.
Lastly, what does the 'true' represent in the 'while'? Does it change to false once I press Ctrl+C/ override it?If you press the link above you will see that a while loop evaluates an expression like while(i < 5) . The expression i<5 is a true or false statement. That is, it evaluates to a boolean. Sometimes it may be true, sometimes it may be false (at which point the loop stops).
The value "true" is basically an expression that's always true (specifically it is a boolean literal). So if I write something like while(true) then I'm making the loop forever ... well loop.
So when he includes
while(true);at the end of the main method, it's equivalent to
while(true) {
   //this will forever loop
//i won't ever get down here

Similar Messages

  • [iPhone SDK] Nib vs. JIT allocation: memory pressure and programmer time

    I'm going to ask a question that there's no single answer to. Instead, I'm more interested to know how different people approach the same problem.
    Lately I've been finding I'm of two minds when I have a UI element or view controller that isn't always used. On the one hand, the iPhone is a fairly memory-constrained environment, and the rules for developing for it are pretty explicit: don't use memory until you need it. That suggests "just in time" or "lazy" allocation: don't allocate it until you actually need it for the first time. After that, hold onto it in case you need it again, but be ready to free it if you receive a memory warning. My code is full of methods with names like "ensureViewerLoaded" which I call just before I need the object in question to allocate it if necessary.
    (For context: my applications are generally UIKit-based utility or data-browsing/editing apps with little graphical or computational complexity and very little memory pressure overall. So far, I've only released one app; at its greediest, it consumes about 1 MB. This isn't because I'm a brilliant programmer--although I do try to be parsimonious--it's just because the app doesn't need much memory to do what it's supposed to do.)
    But on the other hand, allocating those same objects in nib files (or, in other cases, loading them from plists or object archives) makes me more nimble. I've found that it reduces the weight of my code, paring it down to the logic I really need to be paying attention to. That lets me code faster--which means I can modify faster and release faster. And one thing I'm finding is that on the App Store, more releases means more sales. And more sales means I get to buy a MacBook Air with an SSD sooner, and thus save my back a few pounds of strain and my patience a few seconds of compilation. ;^)
    I guess what I'm asking is, how are you resolving these sorts of trade-offs? Where are you trading phone resources for programmer resources, and where are you deciding not to? And how is the type of app you're writing influencing that decision?

    My applications don't need much memory either, so I let everything happen in the nib file. I typically have about three views to worry about, and nothing significantly graphical in any of them.

  • Beginner run-time error

    Hi- I'm an experienced C programmer but trying Java for the first time, following the Sun 'getting started' tutorial. I'm running under Linux.
    I can compile and run the basic 'hello world' example fine, but the trouble starts if I try to do anything with Strings, eg.
    class HelloWorldApp {
        public static void main(String[] args) {
            System.out.println("number of args: " + args.length);
    }No compiler warnings/errors, but when I run (java) it, I get lots of errors starting with:
    Exception in thread "main" java.lang.NoClassDefFoundError: while resolving class: HelloWorldApp
       at java.lang.VMClassLoader.resolveClass(java.lang.Class) (/usr/lib/libgcj.so.5.0.0)
       at java.lang.Class.initializeClass() (/usr/lib/libgcj.so.5.0.0)
       at java.lang.Class.forName(java.lang.String, boolean, java.lang.ClassLoader)
    (/usr/lib/libgcj.so.5.0.0)
       :Obviously I'm doing something stupid, but please could someone tell me what it is?
    Regards,
    John

    matth1j wrote:
    Ok, sorry- I'm stuck. java and javac are both in /usr/bin, as links into /usr/java/jdk1.6.0_05/bin; there's no reference to /usr/java in my .cshrc file. 'which javac' gives me /usr/bin/javac. What do I need to set?That should actually get you the javac from the jdk. Maybe only the java command itself doesn't point to the right location.
    Try those commands:
    java -version
    javac -versionThat should give you the definite answer about what is executed.

  • Beginner Programmer needs help...

    I just have a quick question regarding the get(MINUTE) function in the Calendar class. I am using this to display the current time on a webpage, and every thing seems to work fine except that if the current time has the minutes < 10 (ie, 2:04 or 8:09, etc.) then only that single integer is displayed (2:4, 8:9). I understand why this is happening, but I was wondering if there is a simple way to add a leadign '0' to this int. Here is that section of code...
    int hour = cal.get(Calendar.HOUR);
    int minute = cal.get(Calendar.MINUTE);
    String ampm = (cal.get(Calendar.AM_PM) == 0 ? "AM" : "PM");
    %>
    <p class="body"> Hello <b><%= res.getString("fname") %> <%= res.getString("lname") %></b>.
    It is <b><%= hour+":"+minute+" "+ampm+" on "+mo+"/"+dt+"/"+yr %></b>.</p>
    This page is in JSP. Thanks a lot for the help!

    Replace minute with this. It should format it with a leading zero if needed
    new DecimalFormat("00").format(minute)

  • Can someone check my Class (Beginner programmer)

    Hello, i've been having a tough time writing code with java, and im fairly new to this language. Im trying to create a quiz, and in my class, i have a few error, particularrily where im trying to get a question to randomly select a comment from another method i made called comment.
    tnx
    public class Millionaire
      public Millionaire(double s, int c, String q)
        score = s;
          comment  = c;
      question1 = q;
      public char comment()//A comment based on the number of questions answered correctly
    char c = (char)comment;
        switch(c)
         case '1':
      System.out.println("that's right!, your current earnings are ");
      break;
         case '2':
      System.out.println("Stellar!, you currently have " + " dollars");
      break;
         case '3':
      System.out.println("Amazing!, you currently have " + " dollars");
      break;
         case '4':
      System.out.println("Correct!, your blazing with " + " dollars");
      break;
         case '5':
      System.out.println("Brilliant!, you currently have " + " dollars");
      break;
         default:
      System.out.println(" that's wrong!! you lose!!");
        }           return c;             
    public static String question2;
      System.out.println("Which of these battles did NOT take place during World War I?");
    System.out.println(" A) Somme  B) Ypres C)Vimy Ridge D) D-day");
    String q1;
    q1 = In.getString();
    if (q1=="a")
    score = 10000;
      System.out.println("Great job!!");
    System.out.println(" your current earnings are ");
    comment = math.random(0,5); // dont know if this is correct, this is to pick a random comment from above
    score();
    else
      System.out.println ( "nope that's wrong! you need to be more intact with canadian history");
    public double score()
    double s = 0;
      return score;
    // End of the code
    public double score;
    public int comment;
    public String question1;
    }Edited by: secueritae on Apr 13, 2008 2:42 PM

    Hi, first I suggest you to start with some basics. Learn what are methods, constructors, modifiers, how they work, about main method (you doesn't have it in your code, and you need it), overloading, inheritance, etc., etc.
    Use some IDE like Netbeans, there you have nice features which could help you learn. For example you can place cursor on a method and with alt + F1 you get infromation about it in your browser (you need to install java docs for this to worky).
    [Here: http://java.sun.com/docs/books/tutorial/] you can start.
    Here some working code.import java.io.BufferedReader;
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.Random;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    * @author d3n
    public class Millionaire {
    /*    public Millionaire(double s, int c, String q) {
            score = s;
            comment = c;
            question1 = q;
        public void comment(int comment)//A comment based on the number of questions answered correctly
            switch (comment) {
                case 1:
                    System.out.println("that's right!, your current earnings are ");
                    break;
                case 2:
                    System.out.println("Stellar!, you currently have " + " dollars");
                    break;
                case 3:
                    System.out.println("Amazing!, you currently have " + " dollars");
                    break;
                case 4:
                    System.out.println("Correct!, your blazing with " + " dollars");
                    break;
                case 5:
                    System.out.println("Brilliant!, you currently have " + " dollars");
                    break;
                default:
                    System.out.println(" that's wrong!! you lose!!");
        public void question2() throws IOException {
            System.out.println("Which of these battles did NOT take place during World War I?");
            System.out.println(" A) Somme  B) Ypres C)Vimy Ridge D) D-day");
            String q1;
            q1 = new BufferedReader(new InputStreamReader(System.in)).readLine();
            if (q1.equals(String.valueOf("a")) || q1.equals(String.valueOf("A"))) {
                score = 10000;
                System.out.println("Great job!!");
                System.out.println(" your current earnings are ");
                // dont know if this is correct, this is to pick a random comment from above
                Random r = new Random();
                comment = (Math.abs(r.nextInt()) % 11) % 5 +1;
                comment(comment);
                System.out.println(score());
            } else {
                System.out.println("nope that's wrong! you need to be more intact with canadian history");
        public double score() {
            //double s = 0;
            return score;
    // End of the code
        public double score;
        public int comment;
        public String question1;
        public static void main(String[] args){
            try {
                Millionaire mil = new Millionaire();
                mil.question2();
            } catch (IOException ex) {
                Logger.getLogger(Millionaire.class.getName()).log(Level.SEVERE, null, ex);
    }

  • Beginner programmer just looking for some info...

    Hey, I've posted a couple questions on here already today. And with those questions I've received a lot of great feed back. And I thank all of you for your help. But here's another question, and actually probably more important for me at this time than my other ones. I've just recently started working with Java a little bit. It is the first programming language I've used (other than picking at QBasic way back when, just messing around as a kid). But now I'm extremely interested in programming and was hoping some of you would be able to help me get started. Pointers, tips, suggestions? How did you all get started? Any good tutorials online that could help me? Good book suggestions? Basically, where should I start? Thanks, again, for all of your help!!!

    Any good tutorials online that could help me?http://java.sun.com/docs/books/tutorial/
    Basically, where should I start?Well, most of us probably started by taking classes at school and by doing assignments. If you are doing this on you own then you will need to read and create your own assignments. One way to do this is to find a topic that interests you and then attempt to answer questions in this forum on that topic.
    For example, I was interested in learning how Swing worked, so I read the Swing tutorial from the link given above. Then, to test my knowledge, I tried answering questions on the Swing forum. If I didn't know the answer outright then I would read the API some more, or search the forum to see if the question has been asked before. The more questions I answer, and the more answers I see from other people help me to increase my knowledge. Slowly I increased my knowledgw and have now fooled some people into thinking that I actually know something about Swing.

  • [SOLVED] C/C++ beginner, unix time question

    Hi
    To learn C/C++ I'm trying to make a little space calculator.
    First I would like to calculate the julian date of a given date. Using the Unix time this should be fairly simple.
    (Ignoring calendar changes etc. for now.)
    This is what I did so far:
    // Setting the time manually
    struct tm str_time;
    time_t unix_time; // (time in seconds from 1. Jan 1970 00:00:00 GMT)
    str_time.tm_year = 1970 - 1900; // (years from 1900)
    str_time.tm_mon = 1 - 1; // (month starting at 0)
    str_time.tm_mday = 1;
    str_time.tm_hour = 00;
    str_time.tm_min = 00;
    str_time.tm_sec = 00;
    str_time.tm_isdst = 0;
    unix_time = mktime(&str_time);
    printf("Given time is: %s\n", ctime(&unix_time));
    printf("Unix time: %i s\n", unix_time);
    ctime returns the correct given date Jan 1 00:00:00 1970.
    But the unix_time is -3600.
    Why is there an error of 1h/Shouldn't the unix_time be 0 ?
    Is it wrong to initialize tm this very simple way ?
    Last edited by rebootl (2013-05-25 16:12:33)

    rebootl wrote:
    Thanks. Yes that's correct.
    Then I can correct it by simply doing:
    int unix_time_corr = unix_time+3600;
    However, mktime seems to be limited to 1900-?? or so... so eventually I'll have to find another solution for this...
    This is all a bit intransparent to me.
    For example when I use str_time.tm_year = 1300 - 1900; The year 1300.
    unix_time is 331760832, which is wrong. That's OK cause it's outside the range of mktime (1900-..).
    But then ctime returns: Fri Jan  1 12:00:00 1300, the correct year. How is this possible ?
    1st of all, time_t is 'long unsigned', so your second printf()'s output is faulty. You should always compile with at least '-Wall' to detect those errors.
    As to why ctime() is returning correct date. My 1st suggestion is to read the man pages carefully.
    tm members are "int"s. So, they can accept negative values. ctime(t) is is equivalent to asctime(localtime(t)).
    My guess is that localtime(t) internally casts t to a signed value. And then assigns correct values to tm members. If that's the case. Then what's passed to asctime() is correct.

  • How to make a really basic pong game for a beginner

    Hello.  I've read through a couple of threads on here dealing with making a game of pong in LabView, but in them the users had questions with far more complex aspects of the program than I want to deal with.  I am a beginner programmer in LabView with limited experience in Java and Visual Basic programming.  I was tasked with creating a game over winter break, and now that I finally have some time (this weekend that is), I decided that I'd make a really simple game of pong.  However, I have seriously overestimated the difficulty of this for a beginner who has very limited knowledge of Lab View.
    I ask you to please have some patience with me.
    I know what I want to do, and just need help inplementing it.
    Here is the idea for my design to keep it as simple as possible:
    -Create a field (I am not sure what to use for this, but from my reading it appears that some sort of a picture output is needed, but I cannot find that anywhere).
    -Set up some simple function that can output the dimensions of this field to use with collision tracking.
    -Create a ball that can be tracked by the program.
    -From my reading I understand that the simplest way to "bounce" the ball off the sides appears to simply reverse the X velocity of the ball when it strikes the vertical boundaries and the Y velocity when it strikes the horizontal boundaries.
    -Insert some sort of a "paddle" that the user can control with the left and right arrow keys.
    Now, as I have mentioned I am a beginner with approximately one month maximum knowledge of this software, spread over about a year.  I want to take things slow.  So for starters, would anyone be willing to walk me through creating a visual output for this and creating a ball that will bounce off all sides?
    If I can at least get that far for now, then I can move on (with help I hope!) of inserting an interactive interface for the "paddle."
    I have found some LabView code for a simple game like this, but it also includes a score keeping loop as well as an "automatic play" option, and I am attempting to wade through all that code to find the bones of it to help me with this, but due to my inexperience, this might thake a lot of time.
    I thank you for any and all help anyone may be able to provide.

    EchoWolf wrote:
    -Create a field (I am not sure what to use for this, but from my reading it appears that some sort of a picture output is needed, but I cannot find that anywhere).
     Wel, there is the picture indicator in the picture palette. In newer versions it's called "2D picture". The palettes have a search function. Using the palette search function is a basic LabVIEW skill that you should know. If you've seen the example for the other discussion, it uses a 2D boolean array indicator. The boolean array is only recommended for a monochrome very low resolution display.
    EchoWolf wrote: -Set up some simple function that can output the dimensions of this field to use with collision tracking.
    -Create a ball that can be tracked by the program.
    That seems backwards. Properly programmed, the code always knows the dimension and the ball position. The program generates, (not tracks!) the ball movement. Of course you need to do some range checking on the ball position to see when it collides with the walls.
    EchoWolf wrote:
    -From my reading I understand that the simplest way to "bounce" the ball off the sides appears to simply reverse the X velocity of the ball when it strikes the vertical boundaries and the Y velocity when it strikes the horizontal boundaries.
    Of course you could make it more realistic by keeping track of three ball parameters: x, y, spin.
    EchoWolf wrote:
    -Insert some sort of a "paddle" that the user can control with the left and right arrow keys.
    Pong is typically played with the up-down arrow keys.
    EchoWolf wrote:
    Now, as I have mentioned I am a beginner with approximately one month maximum knowledge of this software, spread over about a year.
    LabVIEW knowledge is not measured in time units. What did you do during that month? Did you attend some lectures, study tutorials, wrote some programs?
    EchoWolf wrote:
    So for starters, would anyone be willing to walk me through creating a visual output for this and creating a ball that will bounce off all sides?
    I have found some LabView code for a simple game like this, but it also includes a score keeping loop as well as an "automatic play" option, and I am attempting to wade through all that code to find the bones of it to help me with this, but due to my inexperience, this might thake a lot of time.
    Start with the posted example and delete all the controls and indicators that you don't want, then surgically remove all code with broken wires.
    Alternatively, start from scratch: Create your playing field. Easiest would be a 2D classic boolean array that is all false. Use initialize array to make it once. Now use a loop to show the ball as a function of time.
    Start with a random ball position. to display it, turn one of the array elements true before wiring to the array indicator using replace array subset.
    Keep a shift register with xy positions and xy velocities and update the positions as a function of the velocities with each iteration of the loop. Do range checking and reverse the velocieis when a edge is encountered.
    What LabVIEW version do you have?
    LabVIEW Champion . Do more with less code and in less time .

  • Stuck on a lap timer

    This is an exercise I have to do and while I don't expect anyone to do the work for me, any suggestions or guidelines will be appreciated more than you know. I think I can handle most of the methods, and have some started and/or finished. I just need to get the startLap going so I can get the rest to work. Code would be great, but I would also appreciate any general guidance on how to make it work. The comments tell what we are to do and there are other classes that work with this. I am just a beginner programmer and am very lost. I am completely blanking on this method. The code thus far is as follows:
    * The timer engine for a lap timer application. This engine can keep
    * track of a 'run'. A run is a sequence of one or more consecutive laps.
    * The timer records single lap times and the time for the total run,
    * and it calculate averages and speed.
    * @author (your name)
    * @version (a version number or a date)
    import java.lang.System;
    public class TimingEngine
    private boolean running;
    private int lapCount;
    private long totalTime;
    private long lastTime;
    private int avgSpeed;
    private int lapLength;
    private long lapStartTime;
    * Create a TimingEngine object. The object will be initialised at 0,
    * status is "Stopped", ready to start timing. The default lap length
    * is 400m.
    public TimingEngine()
    running = false;
    lapCount = 0;
    lastTime = 0;
    totalTime = 0;
    lastTime = 0;
    avgSpeed = 0;
    lapLength = 400;
    * Instruct the timer to start timing a lap.
    * If we were not timing before, this starts the timer for a new
    * run. If we were already timing, this starts a new lap, adding the
    * current lap time to the total.
    public void startLap()
    if(running = false)
    long startTime = getSystemTime();
    startTime = startTime;
    else
    startTime = startTime;
    lapCount++;
    * Stop timing. Add the current lap time to the total, and set
    * the timer into idle mode (waiting for a new run).
    public void stop()
    running = false;
    lastTime = (getSystemTime() - lapStartTime);
    lapStartTime = 0;
    * Return the current status of the timer. The status is one of the
    * two Strings "Timing..." or "Stopped", indicating whether this
    * timer is currently running or stopped.
    public String getStatus()
    if(running = false)
    return "Stopped";
    else
    return "Timing";
    * Return the number of laps completed in this run.
    public int getLapCount()
    return lapCount;
    * Return the time of the last lap completed.
    * The result is a string in the format "m:ss:hh", where m is
    * the number of minutes, ss the number of seconds, and hh the number
    * of hundredths of a second. For example "7:02:43".
    public String getLastTime()
    String lastTimeString = Long.toString(lastTime);
    return lastTimeString;
    * Return the average time for a lap in this run.
    * The result is a string in the format "m:ss:hh".
    public String getAverageTime()
    long averageTime;
    if(lapCount!=0)
    averageTime = totalTime/lapCount;
    else
    averageTime = totalTime;
    String averageTimeString = Long.toString(averageTime);
    return averageTimeString;
    * Return the total time of the last or current run.
    * The result is a string in the format "m:ss:hh".
    public String getTotalTime()
    String totalTimeString = Long.toString(totalTime);
    return totalTimeString;
    * Return the average speed in this run in meters per second.
    * The result is a string such as "73 m/s".
    public String getAverageSpeed()
    return "unfinished";
    * Return the length of a lap.
    public int getLapLength()
    return lapLength;
    * Set the length of a lap.
    public void setLapLength(int length)
    lapLength = length;
    * Private method called whenever a lap is finished. Thsi method
    * updates the statistics.
    private void finishLap()
    * Convert a time interval in milli-seconds into a String in the
    * format "m:ss:hh".
    private String timeToString(long time)
    return "unfinished";
    * Convert a number into a two-digit String representation.
    private String twoDigit(long number)
    //remember there is an example of this in the book!!
    return "unfinished";
    * Return the current time of the system clock (in milli-seconds).
    private long getSystemTime()
    return System.currentTimeMillis();
    }

    This is the newest version of the code that I have been working on. As everyone can see, I really need help. I am on my fifth class of a programming class designed for those who have never programmed and am lost. I have some of it working properly, some not working properly, and some that I haven't attacked yet. The code I haven't started, I am not worried about. I am more concerned about the startLap code and the timeToString code; none of which is working the way it needs to. Any feedback is appreciated. I am using the code tags this time, so hopefully it will be formatted properly.
    * The timer engine for a lap timer application. This engine can keep
    * track of a 'run'. A run is a sequence of one or more consecutive laps.
    * The timer records single lap times and the time for the total run,
    * and it calculate averages and speed.
    * @author (your name)
    * @version (a version number or a date)
    import java.lang.System;
    public class TimingEngine
        private boolean running;
        private int lapCount;
        private long totalTime;
        private long lastTime;
        private int avgSpeed;
        private int lapLength;
        private long lapStartTime;
        private long lapEndTime;
         * Create a TimingEngine object. The object will be initialised at 0,
         * status is "Stopped", ready to start timing. The default lap length
         * is 400m.
        public TimingEngine()
            running = false;
            lapCount = 0;
            lastTime = 0;
            totalTime = 0;
            lastTime = 0;
            avgSpeed = 0;
            lapLength = 400;
            lapStartTime = getSystemTime();
         * Instruct the timer to start timing a lap.
         * If we were not timing before, this starts the timer for a new
         * run. If we were already timing, this starts a new lap, adding the
         * current lap time to the total.
        public void startLap()
           running=true;
           if(getSystemTime()>lapStartTime)
               lastTime=(getSystemTime() - lapStartTime);
           totalTime = (totalTime + lastTime);
           lapStartTime=getSystemTime();
           lapCount++;
         * Stop timing. Add the current lap time to the total, and set
         * the timer into idle mode (waiting for a new run).
        public void stop()
            running = false;
            lastTime = (getSystemTime() - lapStartTime);
            lapStartTime = 0;
         * Return the current status of the timer. The status is one of the
         * two Strings "Timing..." or "Stopped", indicating whether this
         * timer is currently running or stopped.
        public String getStatus()
           if(running = false)
           return "Stopped";
         else
            return "Timing";
         * Return the number of laps completed in this run.
        public int getLapCount()
           return lapCount;
         * Return the time of the last lap completed.
         * The result is a string in the format "m:ss:hh", where m is
         * the number of minutes, ss the number of seconds, and hh the number
         * of hundredths of a second. For example "7:02:43".
        public String getLastTime()
            String lastTimeString = Long.toString(lastTime);
            return lastTimeString;
         * Return the average time for a lap in this run.
         * The result is a string in the format "m:ss:hh".
        public String getAverageTime()
            long averageTime;
            if(lapCount!=0)
                averageTime = totalTime/lapCount;
            else
                averageTime = totalTime;
            String averageTimeString = Long.toString(averageTime);
            return averageTimeString;
         * Return the total time of the last or current run.
         * The result is a string in the format "m:ss:hh".
        public String getTotalTime()
           String totalTimeString = timeToString(totalTime);
           return totalTimeString;
         * Return the average speed in this run in meters per second.
         * The result is a string such as "73 m/s".
        public String getAverageSpeed()
            return "unfinished";
         * Return the length of a lap.
        public int getLapLength()
           return lapLength;
         * Set the length of a lap.
        public void setLapLength(int length)
          lapLength = length; 
         * Private method called whenever a lap is finished. Thsi method
         * updates the statistics.
        private void finishLap()
         * Convert a time interval in milli-seconds into a String in the
         * format "m:ss:hh".
        private String timeToString(long time)
           int totalSeconds;
           int hours;
           int remainingMinutes;
           int minutes;
           int seconds;
           totalSeconds = (int)totalTime/1000;
           hours = totalSeconds/3600;
           remainingMinutes=totalSeconds%3600;
           minutes=remainingMinutes/60;
           seconds = remainingMinutes%60;
           String timeString = Long.toString(hours + minutes +  seconds);
           return timeString;
         * Convert a number into a two-digit String representation.
        private String twoDigit(long number)
          //remember there is an example of this in the book!! 
          return "unfinished";
         * Return the current time of the system clock (in milli-seconds).
        private long getSystemTime()
           return System.currentTimeMillis();
    }

  • Need avice..for beginner with FCP

    I captured all my footage, however when wanted to start editing it asked me to render first which I did. But after I wanted to play my footage in the canvas it told me that some clips were dropped. I reset my canvas on "Full Window" and I was able to see my image on the canvas however the picture was very small - half size of the canvas which makes it really hard to see.
    When I zoom in the picture it either has a terrible quality or it does not work at all and I can only hear the audio.
    Any ideas what I did wrong on settings? Did I maybe made a mistake in shooting the footage wrong?
    Please help..since i'm a beginner (first time my own FCP studio at home) and I don't have much of an idea how to avoid dropped frames and setting my system.
    Thanks!!

    Welcome to the world of FCP.
    First and foremost, you'll find it to be very helpful to use the search feature of this forum for basic question. There's a wealth of knowledge available by doing a simple search.
    For example, a common problem people often encounter when first learning FCP is the need to render clips when they place them in a Sequence. That question gets asked several times a week - so the answer you seek is already here. But to save a bit of time, I'll tell you the most common reason; you're clip's setting do not match your FCP Sequence settings. Anytime that happens, you'll need to render. It would be best to either convert your clip to match the Sequence settings or to create a new Sequence with the setting that will match you clips.
    But after I wanted to play my footage in the canvas it told me that some clips were dropped<<</div>
    Are you certain it didn't say "dropped frames" instead of "dropped clips"?
    When I zoom in the picture it either has a terrible quality or it does not work at all and I can only hear the audio<<</div>
    You cannot upscale video without pixelization and degradation that way. Keep the Canvas an Viewer windows at "Fit to Window" or smaller for proper playback.
    I don't have much of an idea how to avoid dropped frames and setting my system<<</div>
    See this post from earlier today: http://discussions.apple.com/thread.jspa?threadID=893958&tstart=0 Just another example of how searching can help you.
    -DH

  • I'm new and I REALLY need help

    Hi, my name is Chris, I'm new to java.sun.com and I'm a beginner programmer seeking a degree in Comp Sci. I've been writing some code and I've stumbled on some problems that I can't troubleshoot, (run-time?) error seems to be way over my head, the program should work, i don't know why not? Can someone please please give me a clue as to what's going on?
    Here's the program;
    I have to greate a Coins class that will define the different coins (dime, nickelsk, etc.) that will be used in the main .java file. The main .java file has to randomly generate some "change" and sort it out in the least amount of coins possible.
    The problem:
    There are no compilation errors; however, when I run the program I receive this run-time error:
    Exception occurred during event dispatching:
    java.lang.NullPointerException
         at cs130project3.Project3.paint(Project3.java:48)
         at sun.awt.RepaintArea.paint(RepaintArea.java:298)
         at sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:196)
         at java.awt.Component.dispatchEventImpl(Component.java:2663)
         at java.awt.Container.dispatchEventImpl(Container.java:1213)
         at java.awt.Component.dispatchEvent(Component.java:2497)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:339)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:131)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:98)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:85)
    What does this mean?
    Some things I've tried are sticking a g.drawOval() into the paint method, it works just fine, so i assumed there must a problem passing the g object into the coins.draw(g) method, is there a file placement problem or an object passing problem? I'm using Borland JBuilder 7 and i'm assuming that it places the files in the right location, its all in a package called cs130Project3.
    Here is the code:
    Coins class:
    import java.awt.*;
    public class Coins {
    private final int DIAMETER = 30;
    private int coinsAmount = 0;
    private String coinsType = "";
    private int coinsPosX = 0;
    private int coinsPosY = 0;
    public Coins(int coinAmount, String coinType, int coinPosX, int coinPosY) {
    coinsAmount = coinAmount;
    coinsType = coinType;
    coinsPosX = coinPosX;
    coinsPosY = coinPosY;
    public void draw(Graphics screen){
    for(int i = 0; i < coinsAmount; i++)
    screen.drawOval(coinsPosX,coinsPosY,DIAMETER,DIAMETER);
    coinsPosX += 5;
    coinsPosY += 5;
    if(i == (coinsAmount - 1))
    screen.drawString(coinsType,(coinsPosX+10),(coinsPosY+10));
    Here is the main class:
    import java.awt.*;
    import java.util.Random;
    import java.applet.Applet;
    public class Project3 extends Applet {
    private Coins Pennies, Nickels, Dimes, Quarters;
    public void init() {
    int randomChange = 0;
    int numPenny = 0, numNickel = 0, numDime = 0, numQuarter = 0;
    String Penny = "1c", Nickel = "5c", Dime = "10c", Quarter = "25c";
    Random generator = new Random();
    randomChange = generator.nextInt(100);
    while(randomChange > 0)
    while(randomChange >=1)
    while(randomChange >= 5)
    while(randomChange >= 10)
    while(randomChange >= 25)
    numQuarter++;
    randomChange -= 25;
    if(randomChange >= 10)
    numDime++;
    randomChange -= 10;
    if(randomChange >= 5)
    numNickel++;
    randomChange -= 5;
    if(randomChange >= 1)
    numPenny++;
    randomChange -= 1;
    } // End while loop
    Coins Pennies = new Coins(numPenny,Penny,10,10);
    Coins Nickels = new Coins(numNickel,Nickel,100,10);
    Coins Dimes = new Coins(numDime,Dime,150,10);
    Coins Quarters = new Coins(numQuarter,Quarter,200, 10);
    public void paint (Graphics g)
    Pennies.draw(g);
    Nickels.draw(g);
    Dimes.draw(g);
    Quarters.draw(g);
    help me!!
    Thank you,
    Chris

    Chris, I can't even compile your stuff because you didn't post all your classes (Coin is missing), but the runtime error is telling you a lot:
    java.lang.NullPointerException
    at cs130project3.Project3.paint(Project3.java:48)It says you're dereferencing an object that's null at line 48 of your Project3 class. Turn on line numbering in your text editor, go to line 48, and see what you've missed. One of your objects wasn't initialized. I'll bet you declared a reference type in a class but never initialized it properly in a constructor. The JVM will set those references to null unless you provide a value. - MOD

  • Help with a java problem

    Hi
    i am a beginner programmer to java i am trying to solve a problem by writing a prohram but i am totally lost on what to do i was hoping that someone could at least give me a jump start on how top do this program
    basically i am writing a class here is what i need to do:
    i have three .HTML files from edgarscan and this is what i neet to do
    i need to write a class called EdgarWebReportAnalyzer. The
    class should have a single specific constructor that takes one String argument which is the name of a HTML file saved from EdgarScan. You may assume that the file is correctly
    formatted HTML code and arranged similar to the examples above. Then the class
    should have a method called getData(). getData() should take three arguments - an
    int for the year, and int for the quarter, and a String for the row label � and should return
    a String. The return value will depend on whether or not there is data that matches the
    client code arguments.
    If the year and the quarter specified by the arguments is not a column in the file, then the
    return value of getData() should be �no report for that year and quarter�. For example, if
    intelReport is an EdgarWebReportAnalyzer for the intel.htm file above,
    intelReport.getData(2006, 2, �Total Assets, $�) should return �no report for that year and
    quarter�.
    If the row label does not match exactly any of the row labels in the file, then getData()
    should return �that financial info is not reported�. For example, if microsoftReport is an
    EdgarWebReportAnalyzer for the microsoft.htm file above, then microsoftReport.getData(2004, 4, �Long Term Debt, $�) should return �that financial
    info is not reported�.
    If the year and quarter match a column and the row label matches a row, then getData()
    should return a String representing that data, or the empty String if there is no data for
    that column and row
    Thanks a lot hopefully this is enough information i know i dont have any code to start with i am realy lost on what to do but a good jump start or anything that you guys can provide me with will help a lot

    Well, you could start by writing a little class called EdgarWebReortAnalyzer.
    Give it a static main method so you can create an instance and test it.
    Give it a constructor as you are asked to.
    Give it a getData as asked for.
    At the beginning, don't worry about the functionality of those methods; just get what you have there to compile.
    Now it's time to fill in the details.
    I suggest that you look into the various java libraries for XML - in particular for a DOM. This should give you the tools to call - in your constructor - to turn an edgar report file into a DOM. (Maybe not: will an XML parser cleanly parse HTML?)
    Next, when you have figured out how to get your constructor to create a DOM from and edgar file, implement code - in get data - that will walk the DOM for the required data, returning it if it is there.

  • JAVA Applets is CRAP

    Unless there is some1 on the planet that knows how to fix a simple
    problem:
    It has nothing to do with Java code. The problem is with the
    JRE and IE. If you use the HTMLCONVERTER that comes with the SDK
    it converts you applet tags in your html file to object tags. Then
    it works fine. But that does not help the solution. It must work
    with only the applet tags in your html code. I ahve been struggling
    for two weeks now and can't get it working. If you run the demo
    applets that comes with the sdk you'll see it also doesn't work
    unless you apply the HTMLCONVERTER to it. So I AM FEDUP WITH THIS
    CRAP !!! NOBODY SEEM TO KNOW HOW TO FIX THIS &%#@*& PROBLEM !!!
    I HAVE POSTED MESSAGES IN 5 OTHER FORUMS FROM DIFFERENT WEBSITES and
    the best answer I get is to install the latest Java plugin.
    WELL THAT DOESN'T WORK !!!!!!!!!!!
    Java APPLETS SUCK BIGTIME AND I'M FEDUP STRUGGLING !!!
    I suppose thats what you get with "free" software.
    I have tried this problem with IE6 and IE5 on WIN98SE on 3 different PC's. No luck. Sorry guys..... the only solution is to give up you
    programming career.
    from: very fedup beginner programmer (or anti-Java programmer)

    LOL, whatcha talking about?
    Don't learn Java, your problem. Java is slowly becoming the next language, the c++ of today.
    The features are too great to pass up, really:
    portable code,
    cleaner language (though at the expense of some features),
    security (eg. untrusted code in applets),
    USEFUL exception errors
    Trust me, it SUCKS even more in c++ to get seg faults or a crash without any message, and then you have to look for out-of-bounds indexes, % by 0, etc. Java speeds up programming time by a LOT.

  • Java/xml/hashtable-part 2

    Hi, I'm back. I had a question a few days ago using JDOM to read and write XML files with Java, and then creating a hashtable. Someone replied and helped considerably, but as a beginner programmer, I still have a few problems. My XML document is HUGE, with a huge tree and the key and values that i am trying to extract are children of different elements of the tree. Mainly, I am having problems navigating through a tree. Let's say the following is my XML file (mine is much bigger than this but similar problem), and i want the key of the hashtable to be city and the value to be zipcode.
    <?xml version="1.0" ?>
    - <person>
    - <name>
    <firstname>Joe</firstname>
    <lastname>Stevenson</lastname>
    </name>
    - <homeinfo>
    <address street="12345 Jones Lane Avenue" city="Lyndburg" state="Utah" zip="32423" />
    </homeinfo>
    <phone>345-098-2342</phone>
    <email>[email protected]</email>
    <occupation>Secretary</occupation>
    - <workinfo>
    <workname>Senior Citizen's Association</workname>
    <address street="233 Great Street" city="Baltimore" state="Maryland" zip="23421" />
    </workinfo>
    </person>
    So the output i would like to see is: {Lyndburg= 32423, Baltimore=23421}
    Any help would be wonderful! thanks so much!

    As I just wrote, next time please paste your code between code tags exactly like this:
    &#91;code&#93;
    your code
    &#91;/code&#93;
    You may read the [url http://forum.java.sun.com/faq.jsp#format]formatting help for more information.
    Thank you
    I don't know what happened, maybe you didn't copy/paste my code, or made some changes that broke the code. Here is the corrected version of the code you posted:
    import java.io.*;
    import java.util.*;
    import org.jdom.*;
    import org.jdom.input.*;
    import org.jdom.filter.*;
    public class InfoMap {
        public static void main(String[] args) throws Exception {
            new InfoMap().test();
        void test() throws Exception {
            Map map = new HashMap();
            File f = new File("person.xml");
            Document doc = new SAXBuilder().build(f);
            Iterator iterator = doc.getDescendants(new Filter() {
                public boolean matches(Object obj) {
                    if ((obj instanceof Element) && ((Element)obj).getName().equals("person"))
                        return true;
                    else
                        return false;
                } // <-- this was missing
            while (iterator.hasNext()) {
                Element person = (Element)iterator.next();
                Element homeinfo = person.getChild("homeinfo");
                Element address = homeinfo.getChild("address");
                Attribute city = address.getAttribute("city");
                Attribute zip = address.getAttribute("zip");
                map.put(city.getValue(), zip.getValue());
                Element workinfo = person.getChild("workinfo");
                address = workinfo.getChild("address");
                city = address.getAttribute("city");
                zip = address.getAttribute("zip");
                map.put(city.getValue(), zip.getValue());
            System.out.println(map);
        } // <-- this was missing
    } // <-- this was missing

  • Need help with Arrays

    Hey guys, I'm a beginner programmer and I'm having a bit of a tough time with arrays. I could really use some help!
    What I'm trying to do is roll one die and then record the rolls.
    Here is my sample I/O:
    How many times should I roll a die?
    -> 8
    rolling 8 times
    2, 1, 5, 6, 2, 3, 6, 5
    number of 1's: 1
    number of 2's: 2
    and so on....
    Here is my incomplete code at this moment:
    //CountDieFaces.java
    import java.util.Scanner;
    import java.io.*;
    import library.Gamble;
    public class CountDieFaces
        //prompt for and read in: number of times user wants to roll one die
        //simulate rolling a die that many times, counting how many times each face 1 thru 6 comes up
        //print out: each roll
        //AND the total number of times each face occured and the percentage of the time each face occured.
        Scanner scan = new Scanner(System.in);
        int[] faceCount= {0,0,0,0,0,0,0};
        int dice;
        System.out.println("How many times would you like to roll the die?");
        int dieCount = scan.nextInt();
        int dieRoll = Gamble.rollDie(); // Main calling class method
        int count = 1;
        while(count < dieCount)
            System.out.println(faceCount[count]);
            count++;
    }Here is the gamble library:
    //Gamble.java
    package library;
    public class Gamble
         // returns 1, 2, 3, 4, 5, or 6
         public static int rollDie()
              int dieRoll = (int)(Math.random()*6)+1;
              return dieRoll;
    }and here are the errors I have so far:
    ----jGRASP exec: javac -g CountDieFaces.java
    CountDieFaces.java:19: <identifier> expected
         System.out.println("How many times would you like to roll the die?");
         ^
    CountDieFaces.java:19: illegal start of type
         System.out.println("How many times would you like to roll the die?");
         ^
    CountDieFaces.java:25: illegal start of type
         while(count < dieCount)
         ^
    CountDieFaces.java:25: > expected
         while(count < dieCount)
         ^
    CountDieFaces.java:25: ')' expected
         while(count < dieCount)
         ^
    CountDieFaces.java:26: ';' expected
         ^
    CountDieFaces.java:27: illegal start of type
              System.out.println(faceCount[count]);
              ^
    CountDieFaces.java:27: ';' expected
              System.out.println(faceCount[count]);
              ^
    CountDieFaces.java:27: invalid method declaration; return type required
              System.out.println(faceCount[count]);
              ^
    CountDieFaces.java:27: ']' expected
              System.out.println(faceCount[count]);
              ^
    CountDieFaces.java:27: ')' expected
              System.out.println(faceCount[count]);
    I'm really confused with how a the gamble library gets put into the array, so any help is appreciated! Also if anyone could explain the errors to me, I would really appreciate it.
    thanks in advance,
    wootens
    Edited by: Wootens on Oct 18, 2010 8:55 PM

    D'oh!
    Thanks you guys, fixed that. Although I'm having trouble with storing the die roll in the array. Any suggestions?
    java.io.*;
    public class CountDieFaces
        //prompt for and read in: number of times user wants to roll one die
        //simulate rolling a die that many times, counting how many times each face 1 thru 6 comes up
        //print out: each roll
        //AND the total number of times each face occured and the percentage of the time each face occured.
        public static void main(String[] args)
            Scanner scan = new Scanner(System.in);
            int[] faceCount= {0,0,0,0,0,0};
            int dice;
            System.out.println("How many times would you like to roll the die?");
            int dieCount = scan.nextInt();
            int dieRoll = rollDie(); // Main calling class method
            int count = 0;
            while(count < dieCount)
                System.out.println(faceCount[dieRoll]);
                count++;
        public static int rollDie()
            int dieRoll = (int)(Math.random()*6)+1;
            return dieRoll;
    }Wootens

Maybe you are looking for