CSC 224 -- Summary for Day3, June 25, 2001.

Practice Problems

  1. True or False: a static method can call only static methods.
    Answer: This is generally true, but here is a trick. You create a new object of the class containing the static method, then call dynamic methods from this object. For example:
    public class Test
    {
        public static void main(String[] args)
        {
           Test t = new Test();
           System.out.println(t.addOne(5));
        }     public int addOne(int x)
        {
           return x + 1;
        }
    }

  2. True or False: a static method can only be called by static methods. Answer: False, static methods can be called by any method.

  3. What is wrong?

    1 private void main(String args)
    2 {
    3     RepeatSentence("I will eat my spinach.", 20);

    4 private void RepeatSentence(String sentenceToRepeat; int n)
    5     for(i = 1; i <= 20; i =+ 1);
    6     {
    7        System.println(sentenceToRepeat);
    8     }
    9 }

    Answer: Line 1 should be public and static. Also, it should have [ ] after String.
    In Line 3, RepeatSentence should start with a lower case r.
    There should be a closing brace } between lines 3 and 4.
    In Line 4, repeatSentence should be static. There should also be a comma, not a semicolon between String sentenceToRepeat and int n.
    An opening brace should be between lines 4 and 5.
    The variable i must be declared, either in the for statement or between lines 4 and 5.
    The for loop should go from 1 to n, not 1 to 20.
    In Line 5, i =+ 1 should be i += 1, or better yet, i++. There should be no ; at the end of Line 5.
    In Line 7, System.println should be System.out.println.

  4. Write a Java command line application that reads hours, minutes, seconds using the Keyboard class, then prints this information out formatted as a 24 hour time.

    Answer:
    import cs1.Keyboard;
    import java.text.DecimalFormat;

    public class Time
    {
        public static void main(String[] args)
        {
           int h, m, s;
           String h2, m2, s2;
           DecimalFormat f;

           f = new DecimalFormat("00");
           h = Keyboard.readInt();
           m = Keyboard.readInt();
           s = Keyboard.readInt();
           h2 = f.format(h);
           m2 = f.format(m);
           s2 = f.format(s);
           System.out.println(h2 + ":" + m2 + ":" + s2);
        }
    }

  5. Which method do you use to draw a circle in an applet? The center is at (100, 150) and the radius is 50.

    Answer:
    import java.applet.Applet;
    import fava.awt.*;

    public class Circle extends Applet
    {
        public void init()
        {
           setSize(300, 300);
        }
        public void paint(Graphics g)
        {
           g.drawOval(50, 100, 100, 100);
        }
    }

New Topics