Slides16x - Vernonmath.com

Download Report

Transcript Slides16x - Vernonmath.com

Introduction
Correct program design makes the complexity of today's
program requirements possible.
The average student thinks that any program over 1000
lines in length is a large program.
Yet a typical video game
created in the late 1990s
had programs that exceeded
500,000 lines of programming.
These video games are quite small compared to
application programs like CAD and many other popular
application programs.
The Design
Compromise Triangle
The Design
Compromise Triangle
The Design
Compromise Triangle
The Ultimate Priority
Program design becomes a compromise
between speed, memory usage and program
readability.
Program reliability is never a compromise
option. It is a requirement that must be satisfied
with the first program release and all tests are
designed to insure the reliability of a program.
All program considerations revolve around this.
Fundamental
Program
Design
• Write your program in a clear, consistent style.
• Use meaningful, self-documenting identifiers.
• Do not place all your code in the main method.
• Create modules for recognizable tasks.
• Place common purpose modules in a class.
Pre-OOP Program Design
Step #
1
2
3
4
5
Step Mission
Understand the Problem
Develop an Algorithm
Code the Algorithm
Test and Debug the Program
Update and Enhancement
Chess Analogy - 1
Consider Alex.
Alex is the world's
greatest chess player.
Alex is very dissatisfied
with current chess simulation
software and has been quoted as saying:
"I get a better game of chess from the toaster!"
Chess Analogy - 2
Consider Philip.
Philip is the world's
greatest programmer.
Philip is contacted by Alex.
Alex wants to hire him to
write a more challenging
chess program.
Philip has never played chess.
Question: Can Philip write this program?
Chess Analogy - 3
Answer:
NO!
Chess Analogy - 4
Possible Solution:
Consider Brenda.
Brenda has been
programming and
playing chess for
a few years.
She is the perfect
intermediary for
Alex and Philip.
Develop an Algorithm
An algorithm is a step-by-step solution to a given
problem. Of the five steps, this will often be the most
difficult and time-consuming step when program
assignments start becoming complex. Entire
textbooks are devoted to important algorithms.
There will be a future chapter devoted entirely to
popular computer algorithms.
Code the Algorithm
At this stage you need to determine the
programming language that you will use. Java may
not always be the best solution. As you become a
more experienced programmer, you will be able to
select from different languages for different
applications. If the algorithm is well designed, it
should comfortably translate into most programming
languages. Furthermore, keep in mind that coding a
program is not just completed because it works.
Serious considerations need to be given to
efficiency in execution time, in memory usage, and
in program readability.
Test & Debug
After a short introduction in Java you have learned
to become dependent upon the compiler to point out
errors. Keep in mind that the compiler is only
equipped to detect Compile/Syntax errors. Both
Runtime and Logic errors can only be detected
when the program is executed and tested properly.
This step will be addressed again with more detail
after looking at Object Oriented Design.
Update & Enhance
Even programs that are very well planned and
developed properly require updating and enhancing.
Situations arise that were not considered in the
early planning stages and the actual process of
interacting with a working copy of the program often
motivates improvement ideas.
Object Oriented Design
Abstraction - The concept of communicating
about ideas without concern about the
implementation of the ideas.
Once this is done, the programmer needs to
design the appropriate classes.
A good starting point
is to select the "unit"
classes for your program.
In other words, you need
to think bottom-up.
Bottom
Up
Unit Classes
A unit class is a class that contains the
attributes and process method of a single
practical unit.
Classic examples of unit classes are:
Student - Patient - Employee - Card
public class Card
{
private String suit;
private String rank;
private int value;
public Card(String s, String r, int v)
{
suit = s; rank = r; value = v;
}
public String getSuit()
public String getRank()
public int getValue()
public void setSuit(String s)
public void setRank(String r)
public void setValue(int v)
{ return suit; }
{ return rank; }
{ return value; }
{ suit = s; }
{ rank = r; }
{ value = v; }
public String toString() { return "[" + suit + ", " + rank + ", " + value + "]"; }
public boolean matches(Card otherCard)
{
return otherCard.getSuit().equals(this.suit)
&& otherCard.getRank().equals(this.rank)
&& otherCard.getValue() == this.value;
}
}
public class CardTester
{
public static void main(String[] args)
{
Card card1 = new Card("Spades","Seven",7);
Card card2 = new Card("Hearts","King",10);
Card card3 = new Card("Spades","Seven",7);
System.out.println(card1);
System.out.println(card2);
System.out.println(card3);
System.out.println(card1.matches(card2));
System.out.println(card1.matches(card3));
System.out.println(card2.matches(card3));
}
}
// Student.java
// 03-23-15 by Leon Schram
// This is the "Unit" Student class.
// It can become the foundation class of a large School program.
public class Student
{
private String name;
private char sex;
private int age;
private int grade;
public Student(String n, char s, int a, int g)
{
name = n;
sex = s;
age = a;
grade = g;
}
public String getName()
public char getSex()
public int getAge()
public int getGrade()
{ return name; }
{ return sex; }
{ return age; }
{ return grade;}
public void setName(String n)
public void setSex(char s)
public void setAge(int a)
public void setGrade(int g)
{ name = n; }
{ sex = s; }
{ age = a; }
{ grade = g;}
public String toString() { return "[" + name + ", " + sex + ", " + age + ", " + grade + "]"; }
}
// StudentTester.java
// 03-23-15 by Leon Schram
// This class tests the Student class.
// This class does not actually test all the Student methods.
public class StudentTester
{
public static void main(String[] args)
{
Student Stu1 = new Student("Tom",'M',16,10);
Student Stu2 = new Student("Sue",'F',18,12);
Student Stu3 = new Student("Meg",'F',17,11);
System.out.println(Stu1);
System.out.println(Stu2);
System.out.println(Stu3);
}
}
// School.java
// 03-23-15 by Lean Schram
// This class stores Student objects in a students array.
import java.util.ArrayList;
public class School
{
private ArrayList<Student> students;
private int size;
public School()
{ students = new ArrayList<Student>();
public int getSize() { return size; }
public boolean isEmpty() { return size == 0; }
public void add(String name, char sex, int age, int grade)
{
Student temp = new Student(name,sex,age,grade);
students.add(temp);
size++;
}
public String toString()
{
String temp = "";
for (Student student : students)
temp = temp + student.toString() + "\n";
return temp;
}
}
size = 0; }
// SchoolTester.java
// 03-13-15 by Leon Schram
// This program tests the Student class.
public class SchoolTester
{
public static void main(String[] args)
{
School school = new School();
school.add("Sue",'F',14,9);
school.add("Bob",'M',15,10);
school.add("Pat",'F',16,11);
school.add("Joe",'M',17,12);
System.out.println(school);
System.out.println(school.getSize());
System.out.println(school.isEmpty());
}
}
// Deck.java -- Altered 03-23-15 by Leon Schram
// The "Elevens" AP Lab is created for the College Board APCS
// curriculum by Michael Clancy, Robert Glen Martin and Judith Hromcik.
// Leon Schram has altered this "Elevens" AP Lab file to focus on
// CS topics as the "Elevens" Lab is integrated into the curriculum.
import java.util.ArrayList;
public class Deck
{
private ArrayList<Card> cards;
private int size;
public Deck() { cards = new ArrayList<Card>(); size = 0; }
public int getSize() { return size; }
public boolean isEmpty() { return size == 0; }
public void add(String suit, String rank, int value)
{
Card temp = new Card(suit,rank,value);
cards.add(temp);
size++;
}
public String toString()
{
String temp = "";
for (Card card : cards)
temp = temp + card.toString() + "\n";
return temp;
}
}
// DeckTester.java
// Altered 03-23-15 by Lean Schram
// This program tests the Deck class.
// The "Elevens" AP Lab is created for the College Board APCS
// curriculum by Michael Clancy, Robert Glen Martin and Judith Hromcik.
// Leon Schram has altered this "Elevens" AP Lab file to focus on
// CS topics as the "Elevens" Lab is integrated into the curriculum.
public class DeckTester
{
public static void main(String[] args)
{
Deck deck = new Deck();
deck.add("Clubs","Three",3);
deck.add("Diamonds","Four",4);
deck.add("Hearts","Five",5);
deck.add("Spades","Six",6);
System.out.println(deck);
System.out.println(deck.getSize());
System.out.println(deck.isEmpty());
}
}
// Deck.java
// Altered 03-23-15 by Leon Schram
// The Deck class stores and manipulates Card objects.
// This is the student, starting file for Experiment1.
// This file class compiles, but will not execute properly
// with the provided DeckTester class.
//***************************************************************************
// The "Elevens" AP Lab is created for the College Board APCS
// curriculum by Michael Clancy, Robert Glen Martin and Judith Hromcik.
// Leon Schram has altered some of the "Elevens" files to focus on
// specific CS topics as the "Elevens" Lab is integrated into the curriculum.
import java.util.ArrayList;
public class Deck
{
private ArrayList<Card> cards;
private String[] suits = {"Clubs","Diamonds","Hearts","Spades"};
private String[] ranks = {"Two","Three","Four","Five","Six","Seven","Eight","Nine",
"Ten","Jack","Queen","King","Ace"};
private int[] values = {2,3,4,5,6,7,8,9,10,10,10,10,11};
private int deckCount;
private int cardCount;
// Default constructor for card games with 1 deck.
public Deck()
{
deckCount = 1;
cardCount = 52;
cards = new ArrayList<Card>();
for (int suitIndex = 0; suitIndex < 4; suitIndex++)
{
for (int rankIndex = 0; rankIndex < 13; rankIndex++)
{
Card temp = new Card(suits[suitIndex],ranks[rankIndex],values[rankIndex]);
cards.add(temp);
}
}
shuffle();
}
// Overloaded constructor for card games with two or more decks.
public Deck (int dC)
{
deckCount = dC;
cardCount = 52 * deckCount;
}
public int getDeckCount() { return cardCount; }
public int getCardCount() { return cardCount; }
public boolean isEmpty()
{ return cardCount == 0; }
public String toString()
{
String temp = "";
for (Card card : cards)
temp = temp + card.toString() + "\n";
return temp;
}
private void shuffle()
{
for (int k = 1; k < 1000; k++)
{
int random1 = (int) (Math.random() * 52);
int random2 = (int) (Math.random() * 52);
Card temp = cards.get(random1);
cards.set(random1,cards.get(random2));
cards.set(random2,temp);
}
}
}
// DeckTester.java
// Altered 03-23-15 by Leon Schram
// This program tests the Deck class for Experiment1.
// This version will compile, but does not execute properly.
// The "Elevens" AP Lab is created for the College Board APCS
// curriculum by Michael Clancy, Robert Glen Martin and Judith Hromcik.
// Leon Schram has altered some of the "Elevens" files to focus on
// specific CS topics as the "Elevens" Lab is integrated into the curriculum.
public class DeckTester
{
public static void main(String args[])
{
Deck deck = new Deck(2);
System.out.println(deck);
System.out.println("Deck Count: " + deck.getDeckCount());
System.out.println("Card Count: " + deck.getCardCount());
System.out.println(deck.isEmpty());
}
}
Experiment #1 Instructions
Look at the program outputs on the next slide. It
shows what your experiment needs to accomplish.
The previous Deck class had one constructor and the
class was strictly concerned with one deck. This
Deck class has two constructors. The first constructor
has no parameters and is fixed to instantiate a single
deck of 52 cards. The second constructor has a
parameter for the number of decks that are used.
The tester program tests the Deck class for 2 decks.
In this experiment work with your partner and
complete the new Deck class.
Experiment #1 Output
Remember… The first step
is to Understand the Problem
Before you can program the
Elevens lab, you need to learn
to play the Elevens game.
Step 1
Deal 9 Cards
Step 2
Click card pairs that add up to 11.
Note: Ace = 1, Face card = 10
Step 2
Click Replace to get 2 new cards.
Step 3
Repeat.
Step 3
Repeat.
Step 3
Repeat.
Step 4
You can also click JQK triples.
Step 4
As before, click Replace
Step 4
and you get 3 new cards.
Step 5
No 11 pairs or JQK trips left?
Step 6
Eliminate all cards to win.
Step 6
Eliminate all cards to win.
Step 6
Eliminate all cards to win.
File Organization
/**
* Card.java
*
* <code>Card</code> represents a playing card.
************************************************************************
* This is the original AP Elevens Lab Java program code.
* 03-25-15 slightly altered by Leon Schram
* who likes curly braces aligned.
*
Same class as before,
* DO NOT ALTER THIS CLASS!!!!!
*/
but this time the Javadoc
public class Card
comments are included.
{
/**
* String value that holds the suit of the card
*/
private String suit;
/**
* String value that holds the rank of the card
*/
private String rank;
/**
* int value that holds the point value.
*/
private int pointValue;
/**
* Creates a new <code>Card</code> instance.
*
* @param cardRank a <code>String</code> value
*
containing the rank of the card
* @param cardSuit a <code>String</code> value
*
containing the suit of the card
* @param cardPointValue an <code>int</code> value
*
containing the point value of the card
*/
public Card(String cardRank, String cardSuit, int cardPointValue)
{
//initializes a new Card with the given rank, suit, and point value
rank = cardRank;
suit = cardSuit;
pointValue = cardPointValue;
}
/**
* Accesses this <code>Card's</code> suit.
* @return this <code>Card's</code> suit.
*/
public String suit() { return suit; }
/**
* Accesses this <code>Card's</code> rank.
* @return this <code>Card's</code> rank.
*/
public String rank() { return rank; }
/**
* Accesses this <code>Card's</code> point value.
* @return this <code>Card's</code> point value.
*/
public int pointValue() { return pointValue; }
/** Compare this card with the argument.
* @param otherCard the other card to compare to this
* @return true if the rank, suit, and point value of this card
*
are equal to those of the argument;
*
false otherwise.
*/
public boolean matches(Card otherCard)
{
return otherCard.suit().equals(this.suit())
&& otherCard.rank().equals(this.rank())
&& otherCard.pointValue() == this.pointValue();
}
/**
* Converts the rank, suit, and point value into a string in the format
* "[Rank] of [Suit] (point value = [PointValue])".
* This provides a useful way of printing the contents
* of a <code>Deck</code> in an easily readable format or performing
* other similar functions.
*
* @return a <code>String</code> containing the rank, suit,
*
and point value of the card.
*/
@Override
public String toString()
{
return rank + " of " + suit + " (point value = " + pointValue + ")";
}
}
import java.util.List;
import java.util.ArrayList;
/**
* The ElevensBoard class represents the board in a game of Elevens.
************************************************************************
* This is the original AP Elevens Lab Java program code.
* 03-25-15 slightly altered by Leon Schram
* who likes curly braces aligned.
*************************************************************************
* This is the only file that students alter for Lab16.
* This is the student, starting file of Lab16.
*/
public class ElevensBoard
{
/**
* The size (number of cards) on the board.
*/
private static final int BOARD_SIZE = 9;
/**
* The ranks of the cards for this game to be sent to the deck.
*/
private static final String[] RANKS =
{"ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "jack", "queen", "king"};
/**
* The suits of the cards for this game to be sent to the deck.
*/
private static final String[] SUITS =
{"spades", "hearts", "diamonds", "clubs"};
/**
* The values of the cards for this game to be sent to the deck.
*/
private static final int[] POINT_VALUES =
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 0, 0};
/**
* The cards on this board.
*/
private Card[] cards;
/**
* The deck of cards being used to play the current game.
*/
private Deck deck;
/**
* Flag used to control debugging print statements.
*/
private static final boolean I_AM_DEBUGGING = false;
/**
* Creates a new <code>ElevensBoard</code> instance.
*/
public ElevensBoard()
{
cards = new Card[BOARD_SIZE];
deck = new Deck(RANKS, SUITS, POINT_VALUES);
if (I_AM_DEBUGGING)
{
System.out.println(deck);
System.out.println("----------");
}
dealMyCards();
}
/**
* Start a new game by shuffling the deck and
* dealing some cards to this board.
*/
public void newGame()
{
deck.shuffle();
dealMyCards();
}
/**
* Accesses the size of the board.
* Note that this is not the number of cards it contains,
* which will be smaller near the end of a winning game.
* @return the size of the board
*/
public int size()
{
return cards.length;
}
/**
* Determines if the board is empty (has no cards).
* @return true if this board is empty; false otherwise.
*/
public boolean isEmpty()
{
for (int k = 0; k < cards.length; k++)
{
if (cards[k] != null)
{
return false;
}
}
return true;
}
/**
* Deal a card to the kth position in this board.
* If the deck is empty, the kth card is set to null.
* @param k the index of the card to be dealt.
*/
public void deal(int k) { cards[k] = deck.deal(); }
/**
* Accesses the deck's size.
* @return the number of undealt cards left in the deck.
*/
public int deckSize { return deck.size(); }
/**
* Accesses a card on the board.
* @return the card at position k on the board.
* @param k is the board position of the card to return.
*/
public Card cardAt(int k) { return cards[k]; }
/**
* Replaces selected cards on the board by dealing new cards.
* @param selectedCards is a list of the indices of the
*
cards to be replaced.
*/
public void replaceSelectedCards(List<Integer> selectedCards)
{
for (Integer k : selectedCards)
deal(k.intValue());
}
/**
* Gets the indexes of the actual (non-null) cards on the board.
*
* @return a List that contains the locations (indexes)
*
of the non-null entries on the board.
*/
public List<Integer> cardIndexes()
{
List<Integer> selected = new ArrayList<Integer>();
for (int k = 0; k < cards.length; k++)
if (cards[k] != null)
selected.add(new Integer(k));
return selected;
}
/**
* Generates and returns a string representation of this board.
* @return the string version of this board.
*/
public String toString()
{
String s = "";
for (int k = 0; k < cards.length; k++)
{
s = s + k + ": " + cards[k] + "\n";
}
return s;
}
/**
* Determine whether or not the game has been won,
* i.e. neither the board nor the deck has any more cards.
* @return true when the current game has been won;
*
false otherwise.
*/
public boolean gameIsWon()
{
if (deck.isEmpty())
{
for (Card c : cards)
{
if (c != null)
{
return false;
}
}
return true;
}
return false;
}
/**
* Deal cards to this board to start the game.
*/
private void dealMyCards()
{
for (int k = 0; k < cards.length; k++)
{
cards[k] = deck.deal();
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
////// DO NOT CHANGE ANY METHODS ABOVE THIS LINE.
////////////////////////////////////////////////////////////////////////////////////////////////////
///// ONLY ALTER THE METHODS BELOW THIS LINE.
////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Determines if the selected cards form a valid group for removal.
* In Elevens, the legal groups are (1) a pair of non-face cards
* whose values add to 11, and (2) a group of three cards consisting of
* a jack, a queen, and a king in some order.
* @param selectedCards the list of the indices of the selected cards.
* @return true if the selected cards form a valid group for removal;
*
false otherwise.
*/
public boolean isLegal(List<Integer> selectedCards)
{
/* *** TO BE IMPLEMENTED IN LAB16 *** */
return true;
}
/**
* Determine if there are any legal plays left on the board.
* In Elevens, there is a legal play if the board contains
* (1) a pair of non-face cards whose values add to 11, or (2) a group
* of three cards consisting of a jack, a queen, and a king in some order.
* @return true if there is a legal play left on the board;
*
false otherwise.
*/
public boolean anotherPlayIsPossible()
{
/* *** TO BE IMPLEMENTED IN LAB16 *** */
return true;
}
/**
* Check for an 11-pair in the selected cards.
* @param selectedCards selects a subset of this board. It is list
*
of indexes into this board that are searched
*
to find an 11-pair.
* @return true if the board entries in selectedCards
*
contain an 11-pair; false otherwise.
*/
private boolean containsPairSum11(List<Integer> selectedCards)
{
/* *** TO BE IMPLEMENTED IN LAB16 *** */
return true;
}
/**
* Check for a JQK in the selected cards.
* @param selectedCards selects a subset of this board. It is list
*
of indexes into this board that are searched
*
to find a JQK group.
* @return true if the board entries in selectedCards
*
include a jack, a queen, and a king; false otherwise.
*/
private boolean containsJQK(List<Integer> selectedCards)
{
/* *** TO BE IMPLEMENTED IN LAB16 *** */
return true;
}
}
Before we begin…
Before we get too concerned with the program code you need to examine
what the present program code can handle. Load the ElevensGUIRunner
into the edit window of your IDE, compile and then execute the program.
You will be rewarded with the Elevens game display you played earlier.
Go ahead and play the game as you did earlier and consider the following
questions as you play the game?
1.
2.
3.
4.
5.
Does the game respond to the mouse commands?
Try removing the elevens pairs? Does that work correctly?
Try removing the Jack-Queen-King triple. Does that also work?
Play the game to conclusion. Does it continue until you win or lose?
The Elevens game allows only two types of card removals?
Is it possible to remove combination of cards that are different?
6. Go back to the ElevensBoard.java. Look at the four methods.
Does this explain anything?
Computer Error?
Three Types of Errors
There are 3 main types of errors with computer programs:
Syntax/Compile Errors
system,out.pwintlm(Hello"):
Runtime Errors
int[] list = new int [10];
System.out.println(list[20]);
int a = 1;
int b = 0;
int c = a / b;
Logic Errors
int sum = 4 * 6;
System.out.println("4 + 6 = " + sum);
Don’t Be This Type of Student!
Student:
Teacher:
Student:
Teacher:
Student:
Teacher:
Student:
Teacher:
Student:
Teacher:
Can you help me?
Student:
Teacher:
I don’t know. It does not work.
Student:
If I knew what was wrong,
I would not ask for help.
What do you need?
I have a problem.
What type of problem do you have?
My computer has a problem.
What is wrong with your computer?
It does not work.
What is it that does not work?
My program does not work.
What is working or not working
with your program?
You must know what is wrong,
even if you cannot fix the problem.
Compile/Syntax Error Facts
 The compiler will catch all syntax errors.
 The error message is not always an
accurate description of the actual syntax
error.
 The compiler does not necessarily stop
at the correct error location.
Runtime Error Definition
A runtime error or execution error is an
error that interrupts program execution.
This is more popularly known as the
program "crashes".
Exceptions
Java does not use the term runtime errors or
execution errors.
Java has exceptions and all runtime error
messages include the word exception and the
type of exception that has been detected.
There are five common runtime exceptions,
which require closer inspection.
ArithmeticException
An ArithmeticException occurs an attempt is made to
perform an illegal arithmetic operation.
One example occurs when the
program tries to divide by zero.
This error does not occur with
all illegal arithmetic operations.
For instance the statement
System.out.print(Math.sqrt(-10));
does not display an exception message,
but displays NaN, which means “Not a Number”.
// Java1601.java
// This program demonstrates an Arithmetic Exception.
// It also shows that taking the square root of a negative number
// does NOT cause an arithmetic exception.
// Instead, it displays NaN which means "Not a Number".
public class Java1601
{
public static void main(String[] args)
{
System.out.println("The square root of -10 " + Math.sqrt(-10));
System.out.println("1 divided by 0 equals " + quotient(1,0));
}
public static int quotient(int numerator, int denominator)
{
return numerator / denominator;
}
}
IllegalArgumentException
An IllegalArgumentException occurs when
an illegal argument is used for a method call.
When a method is created the programmer can
choose to throw this exception if inappropriate
parameter data is passed to the method.
// Java1602.java
// This program demonstrates a user-created Illegal Argument Exception.
public class Java1602
{
public static void main(String[] args)
{
System.out.println("10 divided by 5 equals " + quotient(10,5));
System.out.println("1 divided by 0 equals " + quotient(1,0));
System.out.println("100 divided by 13 equals " + quotient(100,13));
}
public static int quotient(int numerator, int denominator)
{
if (denominator == 0)
throw new IllegalArgumentException("\nError... Division by Zero");
else
return numerator / denominator;
}
}
ClassCastException
A ClassCastException occurs when
an attempt is made to cast a variable to
a non-matching class.
// This Animal class and its subclasses is used in the next program.
class Animal
{
public Animal() { System.out.println("Animal constructor called"); }
}
class Cat extends Animal
{
protected String catType;
public Cat(String ct)
public String getType()
}
class Bird extends Animal
{
protected String birdType;
public Bird(String bt)
public String getType()
}
class Fish extends Animal
{
protected String fishType;
public Fish(String ft)
public String getType()
}
{ catType = ct;
}
{ return catType; }
{ birdType = bt; }
{ return birdType; }
{ fishType = ft;
}
{ return fishType; }
// Java1603.java
// This program causes a ClassCastException.
public class Java1603
{
public static void main(String args[])
{
Animal tiger = new Cat("Tiger");
System.out.println(((Cat)tiger).getType());
Animal eagle = new Bird("Eagle");
System.out.println(((Bird)eagle).getType());
Animal shark = new Fish ("Shark");
System.out.println(((Cat) shark).getType());
}
}
ArrayIndexOutofBoundsException
An ArrayIndexOutOfBoundsException
occurs when an attempt is made to access an
array with an index outside the range of the
array's indexes.
This error is quite common, because students
frequently forget that the number of elements
in an array is not the same as the largest index
in an array.
// Java1604.java
// This program reviews the ArrayIndexOutOfBoundsException
public class Java1604
{
public static void main(String args[])
{
int[] list = new int [10];
System.out.println(list[10]);
}
}
// Java1605.java
// This program reviews another IndexOutOfBoundsException
import java.util.ArrayList;
public class Java1605
{
public static void main(String[] args)
{
ArrayList<String> names = new ArrayList<String>();
names.add("Sue");
System.out.println(names.get(10));
}
}
NullPointerException
A NullPointerException occurs when an attempt is
made to reference an object using an object variable that
is null.
In a correct situation an object is
a memory reference to a location
where the object's attribute
values can be accessed.
student1
@dff6ccd
dff6ccd
John Smith
If the object's reference
is a null value then any
attempt to access some
attribute field will fail.
student2
@0000000
// This Student class is used in the next program.
class Student
{
private String name;
private int age;
private double gpa;
public Student (String n, int a, double g)
{
name = n; age = a; gpa = g;
}
}
public String getName()
{ return name; }
public int getAge()
{ return age;
}
public double getGPA()
{ return gpa;
}
// Java1606.java
// This program demonstrates a NullPointerException.
public class Java1606
{
public static void main(String[] args)
{
Student stu1 = new Student("Tom",17,3.99);
Student stu2 = null;
System.out.println(stu1.getName());
System.out.println(stu2.getName());
}
}
"There are no pointers in Java."
You will hear several people say this about Java.
Technically, this statement is completely true!
Java has no pointers, but it does have references.
The difference between the two is that a
pointer is declared to store the memory
address of a particular data type.
A reference simply stores a memory address with no
knowledge of what it is pointing to.
NOTE: Java still manages to have NullPointerExceptions
as opposed to NullReferenceExceptions.
AP Exam Alert
Students are expected to understand the common
runtime errors generated by Java, which include:
•
•
•
•
•
NullPointerException
IllegalArgumentException
ArrayIndexOutOfBoundsException
ArithmeticException
ClassCastException
It is not required that students know how to create
exception handling code with throw, try & catch.
Logic Error Definition
A logic error occurs when a program's
output is not logically correct, even though
the program compiles, and the program
executes without crashing.
The careful use of well-chosen test data
catches logic errors.
Program Testing Steps
1. Test the program first with easy to tell test data.
For example, a program that averages student's
grades should start with all grades of 100.
Your average has to be 100.
2. Test the program with a set of test data for which
the correct output is known.
If you average a set of peculiar numbers,
check the answer first on a calculator.
3. Test the program with a wide variety of data, for
every known path that is possible in the program.
4. Test the program carefully with test data at
borderline cases.
Types of Test Data
Minimal Test Data is a set of data that
checks every possible path in a
program, at least once.
Thorough Test Data is a set of data
that checks every possible path in a
program, and checks the border
cases as well, at least once.
Carburetor Logic
Mechanic:
Customer:
Mechanic:
What is wrong with your car?
My car does not start.
Let me check.
Wow, your carburetor is gone.
No wonder your car does not start.
What happened to your carburetor?
Customer: I removed my carburetor.
Mechanic: Why?
Customer: My car would not start.
Mechanic: Your car cannot start without a carburetor.
Customer: My car did not start with the carburetor,
so I removed it.
The Hidden Logic Error
Students often think that a computer with a totally black
screen has “crashed.”
Nothing is showing and nothing is happening.
Frequently, the program is stuck in an infinite loop
without a means to exit.
This is not a runtime error.
The computer is busily
doing what it is told.
This is a logic error.
Information Hiding
Information Hiding is a
computer science tool
that involves using
program features without
the knowledge of how the
program features are
implemented.
Example:
You do not need to know
how to build a car in
order to drive one.
OK, I put the key in the ignition and turn the key. This will complete an
electronic circuit and activate the starter motor. As the starter motor turns
the engine over, the following process brings the car in motion. Fuel is
pumped from the tank to the fuel injectors. The fuel injectors convert the
liquid gas to a fine spray and inject this spray inside the chambers of
each cylinder. The turning of the engine moves the pistons upward inside
the chambers and it compresses the gas into a tight space. With perfect
timing the rotor, inside the distributor, completes an electric circuit that
sends an electric pulse to the appropriate cylinder. The electric pulse is
passed through a spark plug that protrudes inside the cylinder and a
small spark is emitted in the chamber. The compressed gas is ignited by
the spark and explodes. The explosion causes instant expansion and the
piston is driven downward in the cylinder. The piston head is connected
to a piston rod, which moves up and down. The up and down motion of
the piston rod from the repeated explosions is converted to a circular
motion. This circular motion is than transferred to the crankshaft. The
crankshaft continues the energy path to the transmission. The
transmission then selects the appropriate gear for the car movement.
From the transmission the turning force goes by drive shaft and various
universal joints to the differential. The differential distributes the turning
force to the wheels and the car starts to move.
Reasons for
Information Hiding
 There can be valid economic reasons.
 Implementation details may be too
complex and too difficult to understand
 It allows focus on new and different
topics without concern about prior details.