Docsity

Java Programming Lecture Notes: Loops, Methods, and Objects - Prof. Mary Courtney, Assignments of Computer Science

Toggle sidebar
bg1
Computer Science 121
Lecture 1
1. Course overview - syllabus, courseInfo software (http://async.csis.pace.edu/courses/CS122),
grader, tutoring (room 1714)
2. Text: Lewis and Loftus, Java Software Solutions, Addison-Wesley, 1998.
Explain chapters to be covered, appendices - especially appendix O
3. Handout on downloading and configuring JDK (Java 2) and Kawa. Emphasize that they have
to pay for Kawa.
4. Parts of a computer - CPU; Input - mouse, keyboard, disk; Output - monitor, printer, disk;
Disks - hard and floppy; Memory - difference between disks and memory
5. Editing, compiling and running a program - Editor; Compiler - finds syntax errors; Linker -
links in libraries; Run - executes program - must hunt for run-time errors - semantic errors
6. Objects and classes - class defines an object, limited description of object (abstraction) -
application must get 'instances' of the class (object) - done using 'new'
7. Syntax matters - comments (two kinds), assignment, main method, declarations, simple and
complex data, output, constructors
8. Java applications - handout with People class.
// Computer Science 121
// Java application written by <Name>.
// <Date>
// An application with a class that provides information about a person.
class People
{
public static void main (String [ ] args)
{
String name = "Alice";
int age = 7;
// Create a new person with the name 'Alice' and age 7.
person girl = new person (name, age);
// Display information about the person on the screen.
girl.displayAge ( );
} // method main
} // class People
// Class that stores information about a person's name and age.
class person
{
private String name;
private int age;
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e

Partial preview of the text

Download Java Programming Lecture Notes: Loops, Methods, and Objects - Prof. Mary Courtney and more Assignments Computer Science in PDF only on Docsity!

Computer Science 121 Lecture 1

  1. Course overview - syllabus, courseInfo software (http://async.csis.pace.edu/courses/CS122), grader, tutoring (room 1714)
  2. Text: Lewis and Loftus, Java Software Solutions , Addison-Wesley, 1998. Explain chapters to be covered, appendices - especially appendix O
  3. Handout on downloading and configuring JDK (Java 2) and Kawa. Emphasize that they have to pay for Kawa.
  4. Parts of a computer - CPU; Input - mouse, keyboard, disk; Output - monitor, printer, disk; Disks - hard and floppy; Memory - difference between disks and memory
  5. Editing, compiling and running a program - Editor; Compiler - finds syntax errors; Linker - links in libraries; Run - executes program - must hunt for run-time errors - semantic errors
  6. Objects and classes - class defines an object, limited description of object (abstraction) - application must get 'instances' of the class (object) - done using 'new'
  7. Syntax matters - comments (two kinds), assignment, main method, declarations, simple and complex data, output, constructors
  8. Java applications - handout with People class. // Computer Science 121 // Java application written by . // // An application with a class that provides information about a person. class People { public static void main (String [ ] args) { String name = "Alice"; int age = 7; // Create a new person with the name 'Alice' and age 7. person girl = new person (name, age); // Display information about the person on the screen. girl.displayAge ( ); } // method main } // class People // Class that stores information about a person's name and age. class person { private String name; private int age;

public person (String n, int a) { name = n; age = a; } // constructor // Method that displays information about a person. public void displayAge ( ) { System.out.println (name + "'s age is " + age); } // method displayAge } // class person Lecture 3

  1. More on People application - what is an object, class, constructor System.out.print, System.out.println - difference
  2. CityTemps application with errors - how similar to People Lecture 4
  3. People application - constructors
  4. CityTemps application - method that returns a value, constructors
  5. Integer data - byte, short, int, long Expressions - expression sheet
  6. Floating point data - float, double Storage - mantissa, exponent
  7. Character data - Unicode, ascii Boolean data - true, false Lecture 5
  8. Applets - Shapes and NoParking examples API - Application Programming Interface - class libraries, grouped in packages
  9. packages - importing them import java.awt.*; // abstract windowing toolkit - imports all classes import java.applet.Applet // page 673 - imports just the Applet class
  10. paint method drawString (str, x, y) drawOval (x, y, width, height) drawLine (x1, y1, x2, y2)
  11. objects - classes

} // class person // Application for a clerk in a store. import java.io.; import java.text.; // Main class that declares a store clerk and calls the methods. public class Store { public static void main (String [] args) { Clerk storeClerk = new Clerk (); storeClerk.getPrice (); storeClerk.calculateTax (); storeClerk.displayTotal (); } // method main } // class Store // Class that defines a store clerk. class Clerk { private double price, tax, total; // Method that reads the price of a product from the keyboard. public void getPrice () { System.out.print ("Enter the price: "); price = readDouble (); } // method getPrice // Method that calculates the tax. public void calculateTax () { final double taxRate = 0.0825; tax = price * taxRate; } // method calculateTax // Method that calculates and then displays the total bill. public void displayTotal () { total = tax + price; System.out.println ("The total bill is " + decimals (total)); } // method displayTotal // Reads a double from the keyboard and returns it to the calling method. public static double readDouble () { double num; BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in)); try

num = Double.valueOf (stdin.readLine ()).doubleValue (); } catch (IOException e) { num = 0;} return num; } // method readDouble // Formats a double for string output with two decimal places. public static String decimals (double num) { DecimalFormat decFor = new DecimalFormat (); decFor.setMaximumFractionDigits (2); decFor.setMinimumFractionDigits (2); return decFor.format (num); } // method decimals } // class Clerk Lecture 7

  1. Compound conditions and - && or - || not -!
  2. Operator precedence Boolean operators at bottom Use parentheses when uncertain of order Don't use x && y > z. It may not do what you expect.
  3. Char type Letters, ascii, keyboard characters Comparison of characters 'a' < 'z', and 'A' < 'Z'. Also '0' < '9'. Characters have an order given by the order of the character set of the machine.
  4. If - Then statement Tax status example Change example Flow chart
  5. Nested If-Then statements Deciding on a tip depending on service Temperature example - degrees of fever State tax example // Method to analyse a patient's temperature. public classifyTemperature () { System.out.print ( "Enter your temperature. "); temp = readDouble ();

Lecture 8

  1. for statement for (count = 0; count < 10; count ++) { Do something; } // Program to draw a box. public class boxes { public static void main (String [] args) { System.out.println ("**********" ); for (int count = 0; count < 5; count++) System.out.println ("* *" ); System.out.println ("**********" ); } } // class boxes // Program to print a temperature conversion table. public class temperatures { public static void main (String [] args) { int Celsius = 10, Fahrenheit; System.out.println ("Celsius Fahrenheit" ); for (int count = 0; count < 10; count ++) { Fahrenheit = Celsius * 9 / 5 + 32; System.out.println ( "" + Celsius + Fahrenheit ); Celsius = Celsius + 10; } // for } // method main } // class boxes
  2. Running sum - add a fixed number of prices. public class prices { public static void main (String [] args) { double total = 0, price; int no_prices; System.out.print ( "Enter the number of prices: "); no_prices = Reader.readInteger (); for (int count = 0; count < no_prices; count++) { System.out.println ("Price: ");

Price = Reader.readInteger (); total = total + price; } // fir System.out.println ("The total bill is " + total ); } // method main } // class prices no_prices count price total 5 0 1.95 1. 1 3.15 5. 2 2.98 8. 3 .55 8. 4 2.15 10. Lecture 9

  1. While loop Count controlled - like for loop Event controlled - reading to a sentinel Loop may not be done at all.
  2. Off by one errors - importance of boundary conditions
  3. Infinite loops - use and many returns Problems when testing for equality, particularly floats Use { } whenever you must do more than one thing in a loop //Program to illustrate loops public class taxes { public static void main (String [] args) { double taxRate = 0.0825; double price, tax, sum = 0, bill, payment, change; System.out.println ("Enter the prices, end with 0" ); price = Reader.readInteger (); while (price > 0) { sum = sum + price; cin >> price; } System.out.println ("The sum is " + sum ); tax = tax_rate * sum; bill = sum + tax; System.out.println ("The total bill is " + bill );

} // method drawTopBottom // Method to draw the middle of the box. public void drawMiddle () { for (int row = 0; row < height-2; row ++) { System.out.print (''); for (int col = 0; col < width-2; col ++) System.out.print (' '); System.out.println (''); } // for } // method drawMiddle } // class Box Lecture 11

  1. StringTokenizer - page 128 BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in)); StingTokenizer reader = new StringTokenizer (stdin.readLine ()); Reads more than one item (token) on a line. Delimited by white space (space, enter, tab). Returns tokens from a single line read. Must get a new StringTokenizer for each line.
  2. Aliases - one object may be referenced by several names. Discuss pointers again.
  3. Methods - how they are called. Flow of control. Return statement for methods that are not void. Parameters - actual and formal.
  4. Example of a store. // Application for a clerk in a store. import java.io.; import java.text.; // Main class that declares a store clerk and calls the methods. public class Store { public static void main (String [] args) { Clerk storeClerk = new Clerk (); storeClerk.getPrice (); storeClerk.calculateTax (); storeClerk.displayTotal (); } // method main } // class Store

// Class that defines a store clerk. class Clerk { private double price, tax, total; // Method that reads the price of a product from the keyboard. public void getPrice () { System.out.print ("Enter the price: "); price = readDouble (); } // method getPrice // Method that calculates the tax. public void calculateTax () { final double taxRate = 0.0825; tax = price * taxRate; } // method calculateTax // Method that calculates and then displays the total bill. public void displayTotal () { total = tax + price; System.out.println ("The total bill is " + decimals (total)); } // method displayTotal // Reads a double from the keyboard and returns it to the calling method. public static double readDouble () { double num; BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in)); try { num = Double.valueOf (stdin.readLine ()).doubleValue (); } catch (IOException e) { num = 0;} return num; } // method readDouble // Formats a double for string output with two decimal places. public static String decimals (double num) { DecimalFormat decFor = new DecimalFormat (); decFor.setMaximumFractionDigits (2); decFor.setMinimumFractionDigits (2); return decFor.format (num); } // method decimals } // class Clerk

System.out.print ("Price: "); price = readDouble (); sum = sum + price; } // for } // method getOrder // Method that calculates the tax. public double calculateTax () { final double taxRate = 0.0825; tax = sum * taxRate; return tax; } // method calculateTax // Method that calculates and then displays the total bill. public void displayTotal () { tax = calculateTax (); total = tax + sum; System.out.println ("The total bill is " + decimals (total)); } // method displayTotal // Reads a double from the keyboard and returns it to the calling method. public static double readDouble () { double num; BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in)); try { num = Double.valueOf (stdin.readLine ()).doubleValue (); } catch (IOException e) { num = 0;} return num; } // method readDouble // Formats a double for string output with two decimal places. public static String decimals (double num) { DecimalFormat decFor = new DecimalFormat (); decFor.setMaximumFractionDigits (2); decFor.setMinimumFractionDigits (2); return decFor.format (num); } // method decimals // Reads an integer from the keyboard and returns it to the calling method. public static int readInteger () { int num; BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));

try { num = Integer.parseInt (stdin.readLine ()); } catch (IOException e) { num = 0;} return num; } // method readInteger } // class Clerk Lecture 13 Second clerk example // Application for a clerk in a store. import java.io.; import java.text.; // Main class that declares a store clerk and calls the methods. public class Store { public static void main (String [] args) { Clerk storeClerk = new Clerk (); storeClerk.getOrder (); storeClerk.displayTotal (); } // method main } // class Store // Class that defines a store clerk. class Clerk { private double sum, tax, total; int noPrices; public Clerk () { sum = 0; noPrices = 0; } // constructor // Method to read prices from the keyboard, sum them and store the total value. public void getOrder () { double price; System.out.println ("Enter prices, terminate with a zero."); System.out.print ("Price: "); price = readDouble ();

1. Graphics

Drawing figures - rectangles, lines, ovals, colors

  1. Data representation

Doubles and floats, integers, characters, boolean public class TestDoubles { public static void main (String [] args) { double value = 1.0; while (value < 11) { System.out.println ("" + value); value = value + 0.1; } } // method main

  • Lecture
    1. } // class TestDoubles

Lecture 16

  1. Casts - widening and narrowing conversions - no problem with the former, explicit cast required for the latter class TestCast { public static void main (String [] args) { int num = 10; double price = 19.95, value = 30.15; price = num; // Implicit cast - widening. num = (int)value; // Explicit cast - narrowing. System.out.println ("Num " + num); System.out.println ("Price " + price); System.out.println ("Value " + value); } // method main } // class TestCast /* Num 30 Price 10. Value 30. */
  2. Operators Arithmetic - ++ Boolean - &&, ||,! - truth tables Assignment operators - +=, *=, etc. page 187 Conditional operator? - don't use, too confusing, use if-else Precedence - pages 190-
  3. Switch statement - page 189 Note break statement and default case. import java.io.*; class TestSwitch { public static void main (String [] args) { System.out.print ("Enter your answer: "); char answer = readChar (); switch (answer) { case 'y': System.out.println ("Yes"); break; case 'n': System.out.println ("No"); break;

public boolean makeChoice () { boolean quit = false; System.out.print ("Enter your choice: "); choice = Reader.readChar (); switch (choice) { case 'b': case 'B': System.out.println ("Balance"); break; case 'd': case 'D': System.out.println ("Deposit"); break; case 'w': case 'W': System.out.println ("Withdrawal"); break; case 'm': case 'M': displayMenu (); break; case 'q': case 'Q': quit = true; break; default: System.out.println ("Invalid entry - try again"); } // switch return quit; } // method makeChoice; public void makeSeveralChoices () { boolean quit = false; do { displayMenu (); quit = makeChoice (); }while (!quit); System.out.println ("Thank you, come again."); } // method makeSeveralChoices } // class Menu class Reader { // Reads a character from the keyboard and returns it to the calling method. public static char readChar () { char ch; BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in)); try { ch = (char)stdin.read (); } catch (IOException e) { ch = ' ';} return ch; } // method readChar () } // public class Reader Lecture 18

  1. Array declarations Examples: int [] grades = new int [10]; 7 9 4 8 2 6 5 3 1 10 0 1 2 3 4 5 6 7 8 9 double [] averages = new double [10]; String [] names = new String [5];
  2. Accessing elements name [0] = 'S'; grades [5] = 6; averages [3] = 3.2; if (name [0] == 'S') { } while (grades [i] <= 10) { } averages [3] = grades [3] / 4.0;
  3. Using loops to work with arrays for (count = 0; count < 10; count ++) grades [count] = Reader.readInteger (); int size = 0; double [] prices = new double [20]; double price; price = Reader.readDouble (); while (price > 0) { size ++; prices [size] = price; price = Reader.readDouble (); }
  4. Arrays as function arguments public int sumArray (double [] prices, int size) { double sum = 0; for (int count = 0; count < size; count ++) sum = sum + prices [count]; return sum; } // method sumArray
  5. Searching an array for the location of a key value