HELPFUL AND MAYBE USED FOR A TEST OR QUIZ

 

 public class skeleton{
            /*
            name
            class
            date
            assignment
            purpose





            */
            public static void main(String[] args) {
            /*
            place variables here
            */
            

   
        
                
            } // end of main()
}

 

 

EXAMPLES OF TEXTIO, MATH AND STRINGS

 

 

public class Example {
            /*
            name
            class
            date
            assignment
            purpose





            */
  public static void main(String[] args) {





       /*
         b = TextIO.getByte();    // value read is a byte
         i = TextIO.getShort();   // value read is a short
         j = TextIO.getInt();     // value read is an int
         k = TextIO.getLong();    // value read is a long
         x = TextIO.getFloat();   // value read is a float
         y = TextIO.getDouble();  // value read is a double
         a = TextIO.getBoolean(); // value read is a boolean
         c = TextIO.getChar();    // value read is a char
         w = TextIO.getWord();    // value read is a String
         s = TextIO.getln();      // value read is a String
         The Math class contains many static member functions. Here is a list of some
         of the more important of them:
        Math.abs(x), which computes the absolute value of x.
        The exponential function Math.exp(x) for computing the number e raised to the power x,
         and the natural logarithm function Math.log(x) for computing the logarithm of x in
        the base e.
        Math.pow(x,y) for computing x raised to the power y.
        Math.floor(x), which rounds x down to the nearest integer value that is less than or
         equal to x. (For example, Math.floor(3.76) is 3.0.)
        Math.random(), which returns a randomly chosen double in the
        range 0.0 <= Math.random() < 1.0.
        (The computer actually calculates so-called "pseudorandom" numbers
        which are not truly random but are random enough for most purposes.)


         */
         
          int quarters;   // Number of quarters, to be input by the user.
          int dimes;      // Number of dimes, to be input by the user.
          int nickles;    // Number of nickles, to be input by the user.
          int pennies;    // Number of pennies, to be input by the user.
          
          double dollars; // Total value of all the coins, in dollars.
          
          /* Ask the user for the number of each type of coin. */
          
          TextIO.put("Enter the number of quarters:  ");
          quarters = TextIO.getlnInt();
          
          TextIO.put("Enter the number of dimes:     ");
          dimes = TextIO.getlnInt();
          
          TextIO.put("Enter the number of nickles:   ");
          nickles = TextIO.getlnInt();
          TextIO.put("Enter the number of pennies:   ");
          pennies = TextIO.getlnInt();
          
          /* Add up the values of the coins, in dollars. */
          
          dollars = (0.25 * quarters) + (0.10 * dimes) 
                              + (0.05 * nickles) + (0.01 * pennies); 
          
          /* Report the result back to the user. */
          
          TextIO.putln();
          TextIO.putln("The total in dollars is $" + dollars);
          /*
          The String class defines a lot of functions.
        s1.equals(s2) is a function that returns a boolean value.
        It returns true if s1 consists of exactly the same sequence
        of characters as s2, and returns false otherwise.
        s1.equalsIgnoreCase(s2) is another boolean-valued function that
                checks whether s1 is the same string as s2, but this function
                 considers upper and lower case letters to be equivalent.
                 Thus, if s1 is "cat", then s1.equals("Cat") is false,
                 while s1.equalsIgnoreCase("Cat") is true.
        s1.length(), as mentioned above, is an integer-valued function
                that gives the number of characters in s1.
        s1.charAt(N), where N is an integer, returns a value of type char.
                It returns the N-th character in the string. Positions are
                numbered starting with 0, so s1.charAt(0) is the actually
                the first character, s1.charAt(1) is the second, and so on.
                The final position is s1.length() - 1. For example, the value
                of "cat".charAt(1) is 'a'. An error occurs if the value of the
                parameter is less than zero or greater than s1.length() - 1.
        s1.substring(N,M), where N and M are integers, returns a value of type String.
                 The returned value consists of the characters in s1 in positions
                 N, N+1,..., M-1. Note that the character in position M is not included.
                 The returned value is called a substring of s1.
        s1.indexOf(s2) returns an integer. If s2 occurs as a substring of s1, then the
                 returned value is the starting position of that substring. Otherwise,
                 the returned value is -1. You can also use s1.indexOf(ch) to search for
                  a particular character, ch, in s1. To find the first occurrence of x at
                  or after position N, you can use s1.indexOf(x,N).
        s1.compareTo(s2) is an integer-valued function that compares the two strings.
                If the strings are equal, the value returned is zero. If s1 is less than s2,
                 the value returned is a number less than zero, and if s1 is greater than s2,
                  the value returned is some number greater than zero. (If both of the strings
                  consist entirely of lowercase letters, then "less than" and "greater than"
                  refer to alphabetical order. Otherwise, the ordering is more complicated.)
        s1.toUpperCase() is a String-valued function that returns a new string that is equal
                to s1, except that any lower case letters in s1 have been converted to upper
                 case. For example, "Cat".toUpperCase() is the string "CAT". There is also
                 a method s1.toLowerCase().
        s1.trim() is a String-valued function that returns a new string that is equal to s1
                 except that any non-printing characters such as spaces and tabs have been
                  trimmed from the beginning and from the end of the string. Thus, if s1
                   has the value "fred  ", then s1.trim() is the string "fred". 
      */
          
           String usersName;      // The user's name, as entered by the user.
           String upperCaseName;  // The user's name, converted to uppercase letters.
           
           TextIO.put("Please enter your name: ");
           usersName = TextIO.getln();
           
           upperCaseName = usersName.toUpperCase();
           
           TextIO.putln("Hello, " + upperCaseName + ", nice to meet you!");
           /*
           The Math class contains many static member functions. Here is a list of some
         of the more important of them:
        Math.abs(x), which computes the absolute value of x.
                The exponential function Math.exp(x) for computing the number e
                raised to the power x, and the natural logarithm function Math.log(x)
                for computing the logarithm of x in  the base e.
        Math.pow(x,y) for computing x raised to the power y.
        Math.floor(x), which rounds x down to the nearest integer value that is less than or
                equal to x. (For example, Math.floor(3.76) is 3.0.)
        Math.random(), which returns a randomly chosen double in the range
                 0.0 <= Math.random() < 1.0.    (The computer actually calculates so-called
                 "pseudorandom" numbers   which are not truly random but are random enough
                 for most purposes.)
        */


           long startTime; // Starting time of program, in milliseconds.
           long endTime;   // Time when computations are done, in milliseconds.
           double time;    // Time difference, in seconds.
           
           startTime = System.currentTimeMillis();
           
           double width, height, hypotenuse;  // sides of a triangle
           width = 42.0;
           height = 17.0;
           hypotenuse = Math.sqrt( width*width + height*height );
           System.out.print("A triangle with sides 42 and 17 has hypotenuse ");
           System.out.println(hypotenuse);
           
           System.out.println("\nMathematically, sin(x)*sin(x) + " 
                                            + "cos(x)*cos(x) - 1 should be 0.");
           System.out.println("Let's check this for x = 1:");
           System.out.print("      sin(1)*sin(1) + cos(1)*cos(1) - 1 is ");
           System.out.println( Math.sin(1)*Math.sin(1) 
                                             + Math.cos(1)*Math.cos(1) - 1 );
           System.out.println("(There can be round-off errors when " 
                                           + " computing with real numbers!)");
           
           System.out.print("\nHere is a random number:  ");
           System.out.println( Math.random() );
           
           endTime = System.currentTimeMillis();
           time = (endTime - startTime) / 1000.0;
           
           System.out.print("\nRun time in seconds was:  ");
           System.out.println(time);
        
                
            } // end of main()
}

 

IFS

 

if (boolean-expression)
                  statement-1
             else
                  statement-2

 

 

if (boolean-expression-1)
                  statement-1
             else if (boolean-expression-2)
                  statement-2
             else
                  statement-3

 

 

switch (expression) {
             case constant-1:
                statements-1
                break;
             case constant-2:
                statements-2
                break;
                .
                .   // (more cases)
                .
             case constant-N:
                statements-N
                break;
             default:  // optional default case
                statements-(N+1)
          } // end of switch statement

LOOPS

 

          do
              statement
          while ( boolean-expression );

 

initialization
            while ( continuation-condition ) {
                statements
                update
            }

 

for ( variable = min;  variable <= max; variable++ ) {
                 statements
            }

 

public class ListLetters {
        
           /* This program reads a line of text entered by the user.
              It prints a list of the letters that occur in the text,
              and it reports how many different letters were found.
           */
           
           public static void main(String[] args) {
           
              String str;  // Line of text entered by the user.
              int count;   // Number of different letters found in str.
              char letter; // A letter of the alphabet.
              
              TextIO.putln("Please type in a line of text.");
              str = TextIO.getln();
              
              str = str.toUpperCase();
              
              count = 0;
              TextIO.putln("Your input contains the following letters:");
              TextIO.putln();
              TextIO.put("   ");
              for ( letter = 'A'; letter <= 'Z'; letter++ ) {
                  int i;  // Position of a character in str.
                  for ( i = 0; i < str.length(); i++ ) {
                      if ( letter == str.charAt(i) ) {
                          TextIO.put(letter);
                          TextIO.put(' ');
                          count++;
                          break;
                      }
                  }
              }
              
              TextIO.putln();
              TextIO.putln();
              TextIO.putln("There were " + count + " different letters.");
           
           } // end main()
           
        } // end class ListLetters

 

APPLETS

 

 

          import java.awt.*;
          import java.applet.*;
          
          public class name-of-applet extends Applet {
          
              public void paint(Graphics g) {
                 statements
              }
             
          }

 

 

g.setColor(c), is called to set the color that is used for drawing. The parameter, c is an object belonging to a class named Color, another one of the classes in the java.awt package. About a dozen standard colors are available as static member variables in the Color class. These standard colors include Color.black, Color.white, Color.red, Color.green, and Color.blue. For example, if you want to draw in red, you would say "g.setColor(Color.red);". The specified color is used for all drawing operations up until the next time setColor is called.

g.drawRect(x,y,w,h) draws the outline of a rectangle. The parameters x, y, w, and h must be integers. This draws the outline of the rectangle whose top-left corner is x pixels from the left edge of the applet and y pixels down from the top of the applet. The width of the rectangle is w pixels, and the height is h pixels.

g.fillRect(x,y,w,h) is similar to drawRect except that it fills in the inside of the rectangle instead of just drawing an outline.

Now, any console-style applet that you write depends on the ConsoleApplet class, which is not a standard part of Java. This means that the compiled class file, ConsoleApplet.class must be available to your applet when it is run. As a matter of fact, ConsoleApplet uses two other non-standard classes, ConsolePanel and ConsoleCanvas, so the compiled class files ConsolePanel.class and ConsoleCanvas.class must also be available to your applet. This just means that all four class files -- your own class and the three classes it depends on -- must be in the same directory with the source code for the Web page on which your applet appears.

The console is similiar to TextIO except that it is used for applets.

double x,y; // Numbers input by the user.
double prod; // The product, x*y.

console.put("What is your first number? ");
x = console.getlnDouble();
console.put("What is your second number? ");
y = console.getlnDouble();

prod = x * y;
console.putln();
console.put("The product is ");
console.putln(prod);

SIMPLE ANIMATION APPLET --- LETS YOU DO SIMPLE GRAPHICS

import java.awt.*;

public class SimpleRects extends SimpleAnimationApplet {

public void drawFrame(Graphics g) {

// Draw one frame in the animation by filling in the background
// with a solid red and then drawing a set of nested black
// rectangles. The frame number tells how much the first
// rectangle is to be inset from the borders of the applet.

int width; // Width of the applet, in pixels.
int height; // Height of the applet, in pixels.

int inset; // Gap between borders of applet and a rectangle.
// The inset for the outermost rectangle goes
// from 0 to 14 then back to 0, and so on,
// as the frameNumber varies.

int rectWidth, rectHeight; // The size of one of the rectangles.

width = getWidth(); // Find out the size of the drawing area.
height = getHeight();

g.setColor(Color.red); // Fill the frame with red.
g.fillRect(0,0,width,height);

g.setColor(Color.black); // Switch color to black.

inset = getFrameNumber() % 15; // Get the inset for the
// outermost rect.

rectWidth = width - 2*inset - 1; // Set size of outermost rect.
rectHeight = height - 2*inset - 1;

while (rectWidth >= 0 && rectHeight >= 0) {
g.drawRect(inset,inset,rectWidth,rectHeight);
inset += 15; // Rects are 15 pixels apart.
rectWidth -= 30; // Width decreases by 15 pixels
// on left and 15 on right.
rectHeight -= 30; // Height decreases by 15 pixels
// on top and 15 on bottom.
}

} // end drawFrame()

} // end class MovingRects