TCU CoSc 10403 Programming with Java

Download Report

Transcript TCU CoSc 10403 Programming with Java

TCU CoSc 10403
Introduction to Programming
(with Java)
Variables and Methods
Java Identifiers
• Identifiers are the words a programmer uses to identify particular items in
a program.
• They may be used to name a variable (e.g. studentName), a class (e.g.,
HelloWorld or Lab2), or a method (e.g., paint or init).
• Most identifiers have no predefined meaning except as specified by the
programmer.
• Rules & Naming Conventions
– There are rules and naming conventions that are discussed in great
detail in Chapter 6
– Suffice it to say that when you create (instantiate) an object or create a
variable to do arithmetic with – it MUST be declared.
– Java allows the creation of variables to hold integer values, real values,
boolean values, and characters (these are called primitive data types).
***Note: Java is case sensitive. The identifier xyz is not the
same as XYZ.
Variables
•
Declaration
Declaration includes the data
type and a variable name.
Graphics g;
int numCourses;
// integer values
double salesTax;
// floating pt number
Color myColor = new Color(50,100,150);
•
Initialization – assignment for the first time
•
Assignment
name = “Cookie Monster”;
numCourses = 4;
salesTax = 4.75;
•
Assignment changes
the value of a variable..
Variable Reference
String myName;
myName = “Java Guru”;
g.drawString( myName, 0, 12 );
•
Objects
Student tom = new Student(“Tom Jones”);
or
Student tom;
tom = new Student(“Tom Jones”);
3
Slide created by: Professor Elizabeth Boese, “An Introduction to Programming with Java Applets”, Jones and Bartlett Publishers.
Scope: Instance Variable vs. Local Variable
Instance Variable
import javax.swing.*;
import java.awt.*;
public class ColorEx extends JApplet
{
Instance variable:
String favColor;
declared inside the class
String ski;
vs.
Local Variable
import javax.swing.*;
import java.awt.*;
public class ColorEx extends JApplet
{
public void paint( Graphics g )
{
Local variable : declared
inside a method
public void paint( Graphics g )
{
favColor = “Favorite color”;
ski = “Love 2 ski”;
g.setColor( Color.RED );
g.drawString( favColor, 30, 45 );
g.setColor( new Color( 12,34,52)
);
g.drawString( ski, 30, 53 );
}
String favColor = “Favorite
color”;
String ski = “Love 2 ski”;
g.setColor( Color.RED );
g.drawString( favColor, 30, 45 );
g.setColor(new Color( 12,34,52) );
g.drawString( ski, 30, 53 );
}
}
}
4
Slide created by: Professor Elizabeth Boese, “An Introduction to Programming with Java Applets”, Jones and Bartlett Publishers.
Real World Example of a Method
• If you have ever used a recipe to prepare a meal – you may have
advanced to a step in the recipe only to find that you need to refer to
another recipe for something that you need for the meal (say a sauce
that is explained on a different page).
• This way of writing has an import analogue in programming – called
methods in Java.
• The nice thing about this is that important details about the sauce (i.e.,
ingredients, preparation time, etc.) can be hidden from the current
recipe.
• The same is true for programming – regardless of the language being
used.
Methods
• In the context of programming - a method is a list
(sequence) of statements to be performed.
• Methods are used in all programming languages. They are
called different names (e.g., procedures, subroutines,
functions, subprograms, etc.). In Java – they are methods.
• But they all do the same thing – namely, when they are
called (invoked) they run and execute the statements that
are enclosed within them. (e.g., the paint() method).
• They are provided in programming languages as a means
of decomposing large programs of statements into smaller
ones – ones that are more easy to manage and to develop.
return type of void designates the
method doesn’t return anything
•
Methods
Example
public void paint( Graphics g )
{
. . . //executable statements
}
paint is the name of the
method
g is called a “parameter”. Its
type is a Graphics object,
which has methods such as
drawString that we can call
•
Has it’s own scope braces { }
•
•
Statements in method only run when the method is called/invoked
Parameters (none or multiple) listed in parenthesis
– Each must specify the data type and a variable name
– Separate multiple parameters with a comma
paint ( Graphics g )
Student (“John Doe”, 20, “Freshman”);
Color (50, 100, 150);
7
Method Types
Method Types:
•
There are two slightly different forms of methods in Java.
(1) The first receives whatever arguments it is passed, executes the statements in its body, and
returns control of the program where it was first invoked – nothing is passed back! These
take the form:
void
{
methodName(list of arguments)
list of declarations, statements, and inner classes
}
(2) The second receives whatever arguments it is passed, executes the statements in its body,
and returns control of the program where it was first invoked – but passes back some
information.
These take the form:
returnTypeName methodName(list of arguments)
{
list of declarations, statements, and inner classes
return expression
//must be same type as returnTypeName
}
Method – Flow of Control
• You will recall that the init()method is invoked by the system
when you submit the bytecode to the interpreter
• A call to a method places the “called” method into execution.
• When the “called” method reaches the end (or a return statement)
– control is passed by to the “calling” method (just as though there was
no interruption in the execution flow of the invoking method).
Method call that returns a value
The # 2 gets copied into variable num1,
the # 7 gets copied into the variable num2
import java.awt.*;
import javax.swing.*;
The value 9 gets returned to where the
public class Calculate extends JApplet
program called this method
{
public void paint (Graphics g )
{
int addition = getAdd( 2, 7 );
The # 2 gets copied into variable n1,
String added = "2 + 7 = " + addition;
the # 7 gets copied into the variable n2
g.drawString ( added, 0, 12 );
String subtracted = "2 - 7 = " + getSubtract( 2, 7 );
g.drawString ( subtracted, 0, 24 );
}
public int getAdd( int num1, int num2 )
{
return num1 + num2;
}
public int getSubtract( int n1, int n2 )
{
int diff;
diff = n1 - n2;
The value -5 gets returned to where
return diff;
the program called this method
}
}
10
Slide created by: Professor Elizabeth Boese, “An Introduction to Programming with Java Applets”, Jones and Bartlett Publishers.
Why Use Methods?
• Code is easier to read:
• Program decomposition –
– step-wise-refinement
– top-down design
• Repeated code:
• For access by other objects:
• Events: (we’ll discuss later)
11
Why Have Methods?
import java.awt.*;
import javax.swing.*;
public class House extends JApplet
{
public void paint (Graphics g )
{
g.setColor( Color.pink );
g.fillRect ( 100,100,200,200 );
g.setColor( Color.black );
Polygon poly = new Polygon( );
poly.addPoint(100,100);
poly.addPoint(200,50);
poly.addPoint(300,100);
g.fillPolygon(poly);
g.setColor( Color.blue );
g.fillRect ( 200,230,40,70);
g.fillRect ( 120,150,20,30);
g.fillRect ( 150,150,20,30);
g.fillRect ( 200,150,20,30);
g.fillRect ( 230,150,20,30);
Which code
is easier to
figure out
how to add a
new window?
// Code Easier to read: with methods
import java.awt.*;
import javax.swing.*;
public class HouseMethods extends JApplet
{
int WINDOW_WIDTH = 20;
int WINDOW_HEIGHT = 30;
public void paint (Graphics g )
{
paintHouse( g );
paintLandscape( g );
}
public void paintHouse( Graphics grph )
{
grph.setColor( Color.pink );
grph.fillRect ( 100,100,200,200 );
grph.setColor( Color.black );
Polygon poly = new Polygon();
poly.addPoint(100,100);
poly.addPoint(200,50);
poly.addPoint(300,100);
grph.fillPolygon(poly);
grph.setColor( Color.blue );
grph.fillRect ( 200,230,40,70);
paintWindow( grph, 120, 150 );
paintWindow( grph, 150, 150 );
paintWindow( grph, 200, 150 );
paintWindow( grph, 230, 150 );
g.setColor( Color.black );
g.fillRect ( 400,130,30,170 );
g.setColor( Color.green );
g.fillOval( 370,80,100,100 );
g.fillRect ( 0,295,500,5 );
}
public void paintWindow( Graphics gp, int x, int y )
{
gp.setColor( Color.blue );
gp.fillRect ( x, y, WINDOW_WIDTH, WINDOW_HEIGHT );
}
public void paintLandscape( Graphics g )
{
g.setColor( Color.black );
// tree
g.fillRect ( 400,130,30,170 );
g.setColor( Color.green );
g.fillOval( 370,80,100,100 );
g.fillRect ( 0,295,500,5 );
// grass
}
}
}
}
Why Have Methods?
// Repeated code using a method:
import javax.swing.*;
import java.awt.*;
public class NeedMethods
extends JApplet
{
public void paint( Graphics g
)
{
// row 1
g.fillRect( 20,20, 10,10
);
g.fillRect( 40,20, 10,10
);
g.fillRect( 60,20, 10,10
);
g.fillRect( 80,20, 10,10
);
g.fillRect( 100,20, 10,10
);
import javax.swing.*;
import java.awt.*;
public class NeedMethods2 extends JApplet
{
public void paint( Graphics g )
{
drawRows( g, 20, 20 );
drawRows( g, 30, 30 );
}
public void drawRows( Graphics graphics, int x, int y
)
{
graphics.fillRect(
graphics.fillRect(
graphics.fillRect(
graphics.fillRect(
graphics.fillRect(
x,y, 10,10 );
x+20, y, 10, 10
x+40, y, 10, 10
x+60, y, 10, 10
x+80, y, 10, 10
);
);
);
);
}
// row 2
g.fillRect(
);
g.fillRect(
);
g.fillRect(
);
g.fillRect(
);
g.fillRect(
);
}
}
}
30,30, 10,10
50,30, 10,10
70,30, 10,10
90,30, 10,10
Which program would be
easier to use to create a fullsize checkerboard?
110,30, 10,10
13
Why Have Methods?
• Events
– Events in Java are triggered when:
•
•
•
•
•
User selects a button/checkbox/item in list/etc.
User moves/drags the mouse
User types a key
Timer expires
More…
– Each event automatically calls a particular method to handle the
type of event that occurred.
– We’ll discuss events in more detail later
14
Summary
•
•
•
•
Variables
Scope: instance variables vs. local variables
Method Structure
Purpose of methods
15