CPAC Java Procedural Fundamentals COMPLETE
Download
Report
Transcript CPAC Java Procedural Fundamentals COMPLETE
Introduction To Computers and Programming
Lecture 2: Your first program
Professor: Evan Korth
New York University
Road Map for Today
• Syntax vs. style
• Types of errors
• Your First Java Programs!
–
–
–
–
File names and class names
Comments (and why they are important)
The main() method
Outputting text via the standard output object
• Printing Several Lines
• Using Escape Characters
–
–
–
–
Blocks
importing classes from other packages
JOptionPane
System.exit()
• Reading
– Liang 5: finish Chapter 1, Sections 1.9 – 1.12
– Liang 6: finish Chapter 1, Sections 1.8 – 1.11
– Liang 7: finish Chapter 1, Sections 1.8 – 1.10
Review
•
•
•
•
•
•
•
What is a machine language?
What is an assembly language?
What is a high-level programming language?
What are some examples of high-level languages?
What does the term “portable” mean?
What does the Java compiler do?
What is the JVM?
Syntax vs. Style
• Syntax: The rules of a language
• Style: Good programming practices
Errors
• syntax error – Can be picked up by the compiler.
Your program will not compile and the compiler
will try to communicate the location of the error to
you.
• run time or logical error – The compiler cannot
pick up the error because the program is perfectly
legal Java. However, the program does not run as
intended.
A Sample Java Program
• Java uses some notations that may appear strange
at first.
• Let’s look at a sample program.
2.2
A First Program in Java: Printing a
Line of Text
• Application
– Program that executes using the java interpreter
• Sample program
– Show program, then analyze each line
2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
// Fig. 2.1: Welcome1.java
// Text-printing program.
public class Welcome1 {
Outline
Welcome1.java
// main method begins execution of Java application
public static void main( String args[] )
{
System.out.println( "Welcome to Java Programming!" );
} // end method main
} // end class Welcome1
Welcome to Java Programming!
Program Output
2003 Prentice Hall, Inc.
All rights reserved.
2.2
1
A First Program in Java: Printing a
Line of Text
// Fig. 2.1: Welcome1.java
– Comments start with: //
(style)
• Comments ignored during program execution
• Document and describe code
• Provides code readability
– Traditional comments: /* ... */
/* This is a traditional
comment. It can be
split over many lines */
• Common error: When using traditional blocks always
remember to close the comment.
– Javadoc comments: /** ... */
/** This is a special type of comment used
by the javadoc command to automatically
create html documentation of classes,
methods and variables */
2003 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
2.2
2
A First Program in Java: Printing a
Line of Text
// Text-printing program.
– Another line of comments
– Note: line numbers not part of program, added for reference
3
– Blank line (style)
•Makes program more readable
•Blank lines, spaces, and tabs are white-space
characters
–Ignored by compiler
2003 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
2.2
4
A Simple Program: Printing a Line of
Text
public class Welcome1 {
– Begins body of class declaration for class Welcome1
• Every Java program has at least one user-defined class
• Keyword: words reserved for use by Java
– class keyword followed by class name
– Keywords can only be used for intended purpose(s)
• Modifier: defines attributes of classes, methods and variables
– public tells the compiler which methods can access the
method it modifies. For now, all methods will be declared
public.
• Naming classes: capitalize every word (style)
– SampleClassName
2003 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
2.2
4
A Simple Program: Printing a Line of
Text
public class Welcome1 {
– Name of class called identifier
• Series of characters consisting of letters, digits,
underscores ( _ ) and dollar signs ( $ )
• Does not begin with a digit, has no spaces
• Examples: Welcome1, $value, _value, button7
– 7button is invalid
• Java is case sensitive (capitalization matters)
– a1 and A1 are different
• Try to use identifiers that “tell the story” of the program.
– For now, use public keyword
• Certain details not important now
• Mimic certain features, discussions later
2003 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
2.2
4
A Simple Program: Printing a Line of
Text
public class Welcome1 {
– Saving files
• File name must be class name with .java extension
• Welcome1.java
– Left brace {
• Begins body of every class
• Right brace ends class declaration (line 13)
7
public static void main( String args[] )
– Part of every Java application
• Applications begin executing at main
– Parenthesis indicate main is a method
– Java applications contain one or more methods
2003 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
2.2
7
A Simple Program: Printing a Line of
Text
public static void main( String args[] )
• Exactly one method must be called main
– Methods can perform tasks and return information
• void means main returns no information
– More on this later in the semester
• For now, mimic main's first line for subsequent programs
8
{
– Left brace begins body of method declaration for main
method
• Ended by right brace } (line 11)
• Note: Two different acceptable styles in this program.
However, it is bad style to mix these in one program.
2003 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
2.2
9
A Simple Program: Printing a Line of
Text
System.out.println( "Welcome to Java Programming!" );
– Instructs computer to perform an action
• Prints string of characters
– String - series characters inside double quotes
• White-spaces in strings are not ignored by compiler
– System.out
• Standard output object
• Print to command window (i.e., MS-DOS prompt)
– Method System.out.println
• Displays line of text
• Argument inside parenthesis
– This line known as a statement
• A statement is an instruction or a method call
– An instruction is the smallest executable entity within a
programming language
• Statements must end with semicolon ;
2003 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
2.2
11
A Simple Program: Printing a Line of
Text
} // end method main
– Ends method declaration
13
–
–
–
–
} // end class Welcome1
Ends class declaration
Can add comments to keep track of ending braces
Remember, compiler ignores comments
Comments can start on same line after code
2003 Prentice Hall, Inc. All rights reserved.
blocks
• Any code enclosed between braces is called a
block.
• In the previous program there were two blocks.
– The class block (a block is required for a class)
– The method block (a block is required for a method)
• These are just two types of blocks. We will see
others later in the semester.
• Good Programming Habit: Get into the habit of
adding the right brace as soon as you enter the left
brace (then fill in between).
2003 Prentice Hall, Inc. All rights reserved.
2.2
A Simple Program: Printing a Line of
Text
• Compiling a program from the command prompt
– Open a command prompt window, go to directory where
program is stored
– Type javac Welcome1.java
– If no errors, Welcome1.class created
• Has bytecodes that represent application
• Bytecodes passed to Java interpreter
• Let’s see how to compile it with our IDE.
– Compile
– Execute
2003 Prentice Hall, Inc. All rights reserved.
2.2
A Simple Program: Printing a Line of
Text
• Executing a program
– Type java Welcome1
• Interpreter loads .class file for class Welcome1
• .class extension omitted from command
– Interpreter calls method main
Fig. 2.2
Executing Welcome1 in a Microsoft Windows 2000 Command Prompt.
2003 Prentice Hall, Inc. All rights reserved.
2.3
Modifying Our First Java Program
• Modify example in Fig. 2.1 to print same contents
using different code
2003 Prentice Hall, Inc. All rights reserved.
2.3
Modifying Our First Java Program
• Modifying programs
– Welcome2.java (Fig. 2.3) produces same output as
Welcome1.java (Fig. 2.1)
– Using different code
9
10
System.out.print( "Welcome to " );
System.out.println( "Java Programming!" );
– Line 9 displays “Welcome to ” with cursor remaining on
printed line
– Line 10 displays “Java Programming! ” on same line with
cursor on next line
2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Outline
// Fig. 2.3: Welcome2.java
// Printing a line of text with multiple statements.
Welcome2.java
public class Welcome2 {
// main method begins execution of Java application
public static void main( String args[] )
{
System.out.print( "Welcome to " );
System.out.println( "Java Programming!" );
} // end method main
} // end class Welcome2
1. Comments
2. Blank line
3. Begin class
Welcome2
3.1 Method main
System.out.print keeps the cursor on
the same line, so System.out.println
4. Method
continues on the same line.
System.out.prin
t
4.1 Method
System.out.prin
tln
Welcome to Java Programming!
5. end main,
Welcome2
Program
Output
2003 Prentice Hall, Inc.
All rights reserved.
2.3
Modifying Our First Java Program
• Newline characters (\n)
– Interpreted as “special characters” by methods
System.out.print and System.out.println
– Indicates cursor should be on next line
– Welcome3.java (Fig. 2.4)
9
System.out.println( "Welcome\nto\nJava\nProgramming!" );
– Line breaks at \n
• Usage
– Can use in System.out.println or
System.out.print to create new lines
• System.out.println(
"Welcome\nto\nJava\nProgramming!" );
2003 Prentice Hall, Inc. All rights reserved.
Outline
1
2
3
4
5
6
7
8
9
10
11
12
13
// Fig. 2.4: Welcome3.java
// Printing multiple lines of text with a single statement.
Welcome3.java
public class Welcome3 {
1. main
// main method begins execution of Java application
public static void main( String args[] )
{
System.out.println( "Welcome\nto\nJava\nProgramming!" );
} // end method main
2.
System.out.prin
tln (uses \n for new
line)
} // end class Welcome3
Program Output
Welcome
to
Java
Programming!
Notice how a new line is output for each \n
escape sequence.
2003 Prentice Hall, Inc.
All rights reserved.
2.3
Modifying Our First Java Program
Escape characters
– Backslash ( \ )
– Indicates special characters be output
Esc a p e
De sc rip tio n
se q ue nc e
\n
Newline. Position the screen cursor at the beginning of the
next line.
\t
Horizontal tab. Move the screen cursor to the next tab stop.
\r
Carriage return. Position the screen cursor at the beginning of
the current line; do not advance to the next line. Any
characters output after the carriage return overwrite the
characters previously output on that line.
\\
Backslash. Used to print a backslash character.
\"
Double quote. Used to print a double-quote character. For
example,
System.out.println( "\"in quotes\"" );
displays
"in quotes"
Fig. 2.5 So m e c o m m o n e sc a p e se q ue nc e s.
2003 Prentice Hall, Inc. All rights reserved.
2.4
Displaying Text in a Dialog Box
• Display
– Most Java applications use windows or a dialog box
• We have used the command window
– Class JOptionPane allows us to use dialog boxes
• Packages
– Set of predefined classes for us to use
– Groups of related classes called packages
• Group of all packages known as Java class library or Java
applications programming interface (Java API)
– JOptionPane is in the javax.swing package
• Package has classes for using Graphical User Interfaces (GUIs)
2003 Prentice Hall, Inc. All rights reserved.
2.4
Displaying Text in a Dialog Box
• Upcoming program
–
–
–
–
Application that uses dialog boxes
Explanation will come afterwards
Demonstrate another way to display output
Packages, methods and GUI
2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
1// //
Fig.
2.6:
Welcome4.java
Fig.
2.6:
Welcome4.java
// Printing multiple lines in a dialog box.
2 // Printing multiple lines in a dialog box
3// import
javax.swing.JOptionPane; // import class JOptionPane
Java packages
4import javax.swing.JOptionPane; // program uses JOptionPane
5 public class Welcome4 {
public class Welcome4 {
6
public static void main( String args] )
// main method begins execution of Java application
7
{
public static void main( String args[] )
8
JOptionPane.showMessageDialog(
{
JOptionPane.showMessageDialog(
9
null, "Welcome\nto\nJava\nProgramming!" );
null, "Welcome\nto\nJava\nProgramming!" );
10
11
12
System.exit(
0 );
terminate
application
with window
System.exit(
0 );// //
terminate
the program
}
} // end method main
} // end class Welcome4
Outline
Welcome4.java
1. import
declaration
2. Class Welcome4
2.1 main
2.2
showMessageDial
og
2.3 System.exit
Program Output
2003 Prentice Hall, Inc.
All rights reserved.
2.4
Displaying Text in a Dialog Box
– Lines 1-2: comments as before
4
// Java packages
– Two groups of packages in Java API
– Core packages
• Begin with java
• Included with Java 2 Software Development Kit
– Extension packages
• Begin with javax
5
– import declarations
import javax.swing.JOptionPane;
// program uses OptionPane
• Used by compiler to identify and locate classes used in Java
programs
• Tells compiler to load class JOptionPane from
javax.swing package
2003 Prentice Hall, Inc. All rights reserved.
2.4
Displaying Text in a Dialog Box
– Lines 6-11: Blank line, begin class Welcome4 and main
12
13
JOptionPane.showMessageDialog(
null, "Welcome\nto\nJava\nProgramming!" );
– Call method showMessageDialog of class
JOptionPane
• Requires two (or more) arguments
• Multiple arguments separated by commas (,)
• For now, first argument always null
• Second argument is string to display
– showMessageDialog is a static method of class
JOptionPane
• static methods called using class name, dot (.) then method
name
2003 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
2.4
Displaying Text in a Dialog Box
– All statements end with ;
• A single statement can span multiple lines
• Cannot split statement in middle of identifier or string
– Executing lines 12 and 13 displays the dialog box
• Automatically includes an OK button
– Hides or dismisses dialog box
• Title bar has string Message
2003 Prentice Hall, Inc. All rights reserved.
2.4
15
Displaying Text in a Dialog Box
System.exit( 0 );
// terminate application with window
– Calls static method exit of class System
• Terminates application
– Use with any application displaying a GUI
• Because method is static, needs class name and dot (.)
• Identifiers starting with capital letters usually class names
– Argument of 0 means application ended successfully
• Non-zero usually means an error occurred
– Class System part of package java.lang
• No import declaration needed
• java.lang automatically imported in every Java program
– Lines 17-19: Braces to end Welcome4 and main
2003 Prentice Hall, Inc. All rights reserved.
Introduction to Computers and
Programming
Lecture 3: Variables and Input
Professor: Evan Korth
New York University
Road Map for Today
• Variables
– int
– Strings
• Getting input from a user using JOptionPane
• Revisit: Types of errors
• Reading
– Liang 5: Chapter 2, Sections 2.1 – 2.5, 2.14, 2.19
– Liang 6: Chapter 2, Sections 2.1 – 2.5, 2.11, 2.15
– Liang 7: Chapter 2, Sections 2.1 – 2.5, 2.14, 2.16
Review
• What’s wrong with this line of code?
System.out.println
("He said, "Hello"");
• What’s wrong with this program?
public class Welcome1
{
// main method begins execution of Java application
public static void main( String args[] )
{
System.out.println( "Welcome to Java" )
} // end method main
} // end class Welcome1
• What must you name the file for the code above?
Review
• What’s wrong with this program?
public class Welcome
{
public static void main( String args[] )
{
JOptionPane.showMessageDialog(
null, "Welcome to Java!" );
System.exit( 0 );
} // end method main
} // end class Welcome
Variables
Variables
• Variable: a small piece or “chunk” of data.
• Variables enable one to temporarily store data
within a program, and are therefore very useful.
Note: variables are not persistent. When you exit
your program, the data is deleted. To create
persistent data, you must store it to a file system.
Data Types
• Every variable must have two things: a data type and a
name.
• Data Type: defines the kind of data the variable can hold.
– For example, can this variable hold numbers? Can it
hold text?
– Java supports several different data types. We are only
going to look at a few today.
Java’s (primitive) Data Types
• integers: the simplest data type in Java. Used to
hold positive and negative whole numbers, e.g. 5,
25, -777, 1. (Java has several different integer
types)
• Floating point: Used to hold fractional or decimal
values, e.g. 3.14, 10.25. (Java has two different
floating point types)
• chars: Used to hold individual characters, e.g. 'c',
'e', '1', '\n'
• boolean: Used for logic.
• We will explore each one in detail later this
semester.
Bucket Analogy
• It is useful to think of a variable as a bucket of
data.
• The bucket has a unique name, and can only hold
certain kinds of data.
200
balance
balance is a variable
containing the value
200, and can contain
only integers.
Memory Concepts
• Variable names correspond to locations in the
computer’s primary memory.
• Every variable has a name, a type and a value.
• When a value is placed in a memory location the
value replaces the previous value in that location
(called destructive read-in)
• A variable’s value can just be used and not
destroyed (called non-destructive read-out)
Variable Declaration
• Before you use a variable, you must declare it. (Not all
languages require this, but Java certainly does.)
• Examples:
/* Creates an integer variable */
int number;
/* Creates two double variables */
double price, tax;
/* Creates a character variable */
char letter;
semi-colon
data type
identifier
2.2
Rules for identifiers
• Series of characters consisting of letters, digits,
underscores ( _ ) and dollar signs ( $ )
• Does not begin with a digit, has no spaces
• Examples: Welcome1, $value, _value,
button7
– 7button is invalid
• Java is case sensitive (capitalization matters)
– a1 and A1 are different
– Try to use identifiers that “tell the story” of the program.
• Cannot use reserved words
• Try not to redefine identifiers used elsewhere.
2003 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
Reserved Words (added to previous definition of identifiers)
• Certain words have special meaning in Java and cannot be
used as identifiers. These words are called reserved words.
• So far we have seen the following reserved words:
–
–
–
–
–
–
int
public
import
static
void
class
• We will see a complete list of reserved words soon.
• Use of the words null, true and false is also prohibited.
Important Point about Declarations
• In Java you can declare variables at many different places
in the program. They have different meaning and scope
depending on where they are declared. For now, we will
declare all our variables at the beginning of main().
public class Sample {
public static void main(String args[])
{
declare variables here
executable statements here
} // end method main
} // end class Sample
Example 1: Basic Arithmetic
/* Illustrates Integer Variables */
public class Sample {
public static void main(String args[])
Variable Declarations
{
int x;
Variable Name
int y;
int z;
semicolon
Data Type
x = 5;
y = 10;
z = x + y;
Assignment Statements
System.out.println ("x:
System.out.println ("y:
System.out.println ("z:
} // end method main
} // end class Sample
" + x);
" + y);
" + z);
x:
y:
z:
5
10
15
Assignment Statements
• Assignment statements enable one to assign (initial or not)
values to variables or perform basic arithmetic.
x = 5;
y = 10;
z = x + y;
• Here, we simply initialize x and y and store their sum
within the variable z.
Note: If you forget to initialize your variables, the
variable may contain any value. This is referred to as a
garbage value. Hence, always initialize your variables!
Java enforces this rule; but, not all languages do.
Assignment Operator
• =
• Read the assignment operator as “GETS” not
“EQUALS!”
• This is an assignment of what’s on the right side
of = to a variable on the left
• eg sum = integer1 + integer2;
– Read this as, “sum gets integer1 + integer2”
– integer1 and integer2 are added together and stored in sum
Printing Variables
• To print a variable, use the System.out.print or
System.out.println statement as you would for a
string.
System.out.print (x);
System.out.println (x);
System.out.println ("x:
" + x);
Here the “addition” that
is performed is string
concatenation.
Initialization
• When you declare a primitive variable, you do not
know the value stored in that variable until you
place something there. The language specification
does not guarantee any initial value.
• Until the user initializes the value, the value stored
in that memory is called a garbage value.
• Java will not allow you to use the garbage value in
a calculation or for output. If it is possible that a
variable has not been initialized when you try to
use it, you will get a compilation error.
• So you must initialize the variable before you use
it on the right hand side of a calculation or output
it to the screen.
Good Programming Style
Choose meaningful variable names to make your
program more readable. For example, use income,
instead of num.
Stick to lower-case variable names. For example, use
income, instead of INCOME. Variables that are all
capitals usually indicate a constant (more on this
soon.)
Use "proper case" for all words after the first in a
variable name. For example, instead of
totalcommissions, use totalCommissions.
Avoid redefining identifiers previously defined in the
Java API.
Revisit Errors
Syntax Errors
• Caused when the compiler cannot recognize a
statement.
• These are violations of the language
• The compiler normally issues an error message to
help the programmer locate and fix it
• Also called compile errors or compile-time errors.
• For example, if you forget a semi-colon, you will
get a syntax error.
Run-time Errors
• The compiler cannot pick up on runtime errors.
Therefore they happen at runtime.
• Runtime errors fall into two categories.
– Fatal runtime errors: These errors cause your program to
crash.
– Logic errors: The program can run but the results are not
correct.
2.5
Another Java Application: Adding
Integers
• Upcoming program
– Use input dialogs to input two values from user
– Use message dialog to display sum of the two values
2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Fig. 2.9: Addition.java
// Addition program that displays the sum of two numbers.
// Java packages
import javax.swing.JOptionPane;
Outline
Addition.java
// program uses JOptionPane
1. import
public class Addition {
name and
// main method begins executionDeclare
of Javavariables:
application
public static void main( String args[] )
{
String firstNumber;
// first string entered by user
String secondNumber; // second string entered by user
int number1;
int number2;
int sum;
type.
// first number to add
Input
first integer
// second
number
to add as a String,
// sum to
offirstNumber.
number1 and number2
2.1 Declare variables
(name and type)
assign
// read in first number from user as a String
firstNumber = JOptionPane.showInputDialog( "Enter first integer" );
// read in second number from user as a String
secondNumber =
JOptionPane.showInputDialog( "Enter second integer" );
2. class Addition
3.
showInputDialog
4. parseInt
5. Add numbers, put
result in sum
Convert strings to integers.
// convert numbers from type StringAdd,
to type
placeint
result
number1 = Integer.parseInt( firstNumber );
number2 = Integer.parseInt( secondNumber );
// add numbers
sum = number1 + number2;
in sum.
2003 Prentice Hall, Inc.
All rights reserved.
33
34
35
36
37
38
39
40
41
// display result
JOptionPane.showMessageDialog( null, "The sum is " + sum,
"Results", JOptionPane.PLAIN_MESSAGE );
System.exit( 0 );
Outline
// terminate application with window
} // end method main
} // end class Addition
Program output
2003 Prentice Hall, Inc.
All rights reserved.
2.5
5
Another Java Application: Adding
Integers
import javax.swing.JOptionPane;
// program uses JOptionPane
– Location of JOptionPane for use in the program
7
public class Addition {
– Begins public class Addition
• Recall that file name must be Addition.java
– Lines 10-11: main
12
13
String firstNumber;
String secondNumber;
// first string entered by user
// second string entered by user
– Declaration
• firstNumber and secondNumber are variables
2003 Prentice Hall, Inc. All rights reserved.
2.5
12
13
Another Java Application: Adding
Integers
String firstNumber;
String secondNumber;
// first string entered by user
// second string entered by user
– Variables
• Location in memory that stores a value
– Declare with name and type before use
• firstNumber and secondNumber are of type String
(package java.lang)
– Hold strings
• Variable name: any valid identifier
• Declarations end with semicolons ;
String firstNumber, secondNumber;
– Can declare multiple variables of the same type at a time
– Use comma separated list
– Can add comments to describe purpose of variables
2003 Prentice Hall, Inc. All rights reserved.
2.5
15
16
17
Another Java Application: Adding
Integers
int number1;
int number2;
int sum;
// first number to add
// second number to add
// sum of number1 and number2
– Declares variables number1, number2, and sum of type
int
• int holds integer values (whole numbers): i.e., 0, -4, 97
• Types float and double can hold decimal numbers
• Type char can hold a single character: i.e., 'x', '$', '\n', '7'
• Primitive types
2003 Prentice Hall, Inc. All rights reserved.
2.5
20
Another Java Application: Adding
Integers
firstNumber = JOptionPane.showInputDialog( "Enter first integer" );
– Reads String from the user, representing the first number
to be added
• Method JOptionPane.showInputDialog displays the
following:
• Message called a prompt - directs user to perform an action
• Argument appears as prompt text
• If you click Cancel, error occurs
2003 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
2.5
20
Another Java Application: Adding
Integers
firstNumber = JOptionPane.showInputDialog( "Enter first integer" );
– Result of call to showInputDialog given to
firstNumber using assignment operator =
• Assignment statement
• = binary operator - takes two operands
– Expression on right evaluated and assigned to variable on
left
• Read as: firstNumber gets value of
JOptionPane.showInputDialog( "Enter first
integer" )
2003 Prentice Hall, Inc. All rights reserved.
2.5
23
24
Another Java Application: Adding
Integers
secondNumber =
JOptionPane.showInputDialog( "Enter second integer" );
– Similar to previous statement
• Assigns variable secondNumber to second integer input
27
28
number1 = Integer.parseInt( firstNumber );
number2 = Integer.parseInt( secondNumber );
– Method Integer.parseInt
• Converts String argument into an integer (type int)
– Class Integer in java.lang
• Integer returned by Integer.parseInt is assigned to
variable number1 (line 27)
– Remember that number1 was declared as type int
– If a non-integer value was entered an error will occur
• Line 28 similar
2003 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
2.5
31
Another Java Application: Adding
Integers
sum = number1 + number2;
– Assignment statement
• Calculates sum of number1 and number2 (right hand side)
• Uses assignment operator = to assign result to variable sum
(left hand side)
• Read as: sum gets the value of number1 + number2
• number1 and number2 are operands
2003 Prentice Hall, Inc. All rights reserved.
2.5
34
35
Another Java Application: Adding
Integers
JOptionPane.showMessageDialog( null, "The sum is " + sum,
"Results", JOptionPane.PLAIN_MESSAGE );
– Use showMessageDialog to display results
– "The sum is " + sum
• Uses the operator + to "add" the string literal "The sum is"
and sum
• Concatenation of a String and another type
– Results in a new string
• If sum contains 117, then "The sum is " + sum results in
the new string "The sum is 117"
• Note the space in "The sum is "
• More on strings later
2003 Prentice Hall, Inc. All rights reserved.
2.5
34
35
Another Java Application: Adding
Integers
JOptionPane.showMessageDialog( null, "The sum is " + sum,
"Results", JOptionPane.PLAIN_MESSAGE );
– Different version of showMessageDialog
•
•
•
•
•
Requires four arguments (instead of two as before)
First argument: null for now
Second: string to display
Third: string in title bar
Fourth: type of message dialog with icon
– Line 35 no icon: JOptionPane.PLAIN_MESSAGE
2003 Prentice Hall, Inc. All rights reserved.
2.5
Another Java Application: Adding
Integers
Messa g e d ia lo g typ e
Ic o n
Desc rip tio n
JOptionPane.ERROR_MESSAGE
Displays a dialog that indicates an error
to the user.
JOptionPane.INFORMATION_MESSAGE
Displays a dialog with an informational
message to the user. The user can simply
dismiss the dialog.
JOptionPane.WARNING_MESSAGE
Displays a dialog that warns the user of a
potential problem.
JOptionPane.QUESTION_MESSAGE
Displays a dialog that poses a question to
the user. This dialog normally requires a
response, such as clicking on a Yes or a
No button.
JOptionPane.PLAIN_MESSAGE
Displays a dialog that simply contains a
message, with no icon.
Fig. 2.12 JOptionPane c o nsta nts fo r m essa g e d ia lo g s.
2003 Prentice Hall, Inc. All rights reserved.
no icon
Introduction to Computers and
Programming
Lecture 4: Mathematical Operators
Professor: Evan Korth
New York University
Road Map
•
•
•
•
•
•
Constants
Basic Mathematical Operators
Integer Division
Operator Precedence
Floating point types
Other integer types
• Reading:
– Liang 5: Chapter 2: 2.6, 2.7 (excluding 2.7.4), 2.8, 2.11
– Liang 6: Chapter 2: 2.6, 2.7 (excluding 2.7.4), 2.8 plus part
of 3.7
– Liang 7: Chapter 2: : 2.6, 2.7 (excluding 2.7.4), 2.8 plus part
of 3.7
•
•
•
•
•
•
Review – True / False
When System.out.println is called, it always
begins printing at the beginning of a new line.
All variables must be declared before they are
used.
All variables must be given a type when they are
declared.
Java considers the variables number and NuMBer
identical.
Declarations can appear anywhere in the body of
the method main().
A Java program that prints three lines of output
must contain three System.out.println()
statements.
Review
1.
Find the error in each statement:
• System.println (″The value is ″ +
value); /*assume there is an int
variable called value that has been
initialized*/
• int num1, int num2, int num3;
• int num#1, num#2, num#3;
2. What is the output for the following Java statements:
int x;
x = x+1;
System.out.println (x);
3.
What is the difference between a compile-time and runtime error?
Basic Mathematical Operators
Basic Mathematical Operators
Java
Operation
Addition
Arithmetic Algebraic Java
Operator
Expression Expression
+
a+b
a+b
Subtraction
-
a–b
a–b
Multiplication
*
ab
a*b
Division
/
a/b
a/b
Modulus
%
a mod b
a%b
Each of the operators in the table are binary operators. A binary operator acts
on two operands
Integer Division - The Problem
• Suppose you have the following code:
int x;
x = 7 / 4;
• Using a calculator, the answer is 1.75.
• But x can only hold integer values. 1.75 is clearly
not an integer value.
Integer Division - Solution
• To understand the solution, you need to remember
your 3rd Grade Math (really.)
1
4
7
4
3
The answer: 1 remainder 3
• 7/4 = 1 (Integer Division)
• 7%4 = 3 (Modulus Division)
Example: Integer Division
// Integer and Modulus Division
public class DivMod
{
public static void main( String args[] )
{
int x = 5, y = 10;
System.out.println ("5 / 10: " + x/y);
System.out.println ("5 % 10: " + x%y);
}
}
5 / 10: 0
5 % 10: 5
Modulus Division (cont.)
• Second Example:
5/10 = 0
5%10 = 5
1
0
0
5
0
5
• No matter what, your answers must be integers.
Odd / Even Numbers
• Modulus division can also be used to determine
whether a number is odd or even.
• Just divide by 2. If the remainder (modulus) is 0,
the number is even.
• Examples:
– 10 % 2 = 0. Hence 10 is even.
– 11 % 2 = 1. Hence 11 is odd.
Common Programming Error: Dividing by zero
is
normally undefined on computer systems and
generally results in a fatal error.
Operator Precedence
Operator Precedence
• Here’s another problem. What’s the answer to this?
x = 7 + 3 * 6;
• Two Options (depending on the order of operations):
Perform addition first: 7 + 3 = 10 10
* 6 = 60
Perform multiplication first: 3*6 =18
7+18 = 25
• Which option is correct? Clearly, we cannot have this kind
of ambiguity.
Operator Precedence
• Operator precedence represent rules for evaluating
mathematical expressions.
• Every programming language has similar rules.
Operator(s)
()
Operation(s)
Parentheses
*, /, or %
Multiplication
Division
Modulus
Addition
Subtraction
+ or -
2003 Prentice Hall, Inc. All rights reserved.
Order of evaluation (precedence)
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs of parentheses “on the same level” (i.e.,
not nested), they are evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right.
Evaluated last. If there are several, they are
evaluated left to right.
Operator Precedence
• Hence, option #2 is always correct (multiplication
is performed first):
x = 7 + 3 * 6;
Evaluates to x = 7 + 18 = 25
• Example: Find the average of three variables a, b
and c
• Do not use: a + b + c / 3
• Use: (a + b + c ) / 3
Parentheses
• Are your friends
• Are your really good friends
• Because with them you can ensure expressions
are evaluated as you expect
• Can avoid mistakes with operator precedence
(one less thing to think about)
– e.g. y
y
– e.g. y
y
=
=
=
=
m * x + b
(m * x) +
a * b * b
(((a * b)
;
b;
+ c * b – d;
* b) + (c * b)) – d;
Floating Point Data Types
double Data Type
• Data type that can hold numbers with fractional
values
– e.g. 3.14, 98.6
• Doubles can be used to represent many values:
– Money (but see warning below)
– distance
– weight, etc.
double Example
// Double Example Program
public class Double
{
public static void main( String args[] )
{
double var1, var2, var3, sum;
var1 = 87.25;
var2 = 92.50;
var3 = 96.75;
sum = var1 + var2 + var3;
System.out.println ("Sum:
}
}
" + sum);
Sum:
276.5
Numeric type ranges in Java
Integers
byt e
shor t
i nt
l ong
8 bits
16 bits
32 bits
64 bits
-128
-32768
-2,147,483,648
-9,223,372,036,854,770,000
127
32767
2,147,483,647
9,223,372,036,854,770,000
Floating point values
float
double
32 -3.40282347E+38
64 -1.79769313486231570E+308
3.40282347E+38
1.79769313486231570E+308
Example: Find an Average
• Suppose you want to determine a student’s
average.
int totalTests = 4;
double average = 90+92+95+100/ totalTests;
Example: Find an Average
• Problem #1: Operator Precedence
– By rules of operator precedence, 100/4 is evaluated first. Hence,
average is set to: 302.
– To solve this problem, use ():
int totalTests = 4;
double average = (90+92+95+100)/ totalTests;
Example: Find an Average
• Problem #2:
– 90, 92, 95, 100 and 4 are all integers. Hence, this is integer
division.
– Integer division can result in data truncation (or loss of data.)
– Hence, average is set to: 94.0, but the students real average
is 94.25.
– There are actually three ways to solve this problem.
Rules of Promotion
• Promotion: when mixing integers and doubles, all
the values are promoted to doubles.
• In our average example, there are three ways to
force promotion, and get the right answer of
94.25:
1. change totalTests to a double:
double totalTests = 4.0;
double average = (90+92+95+100)/ totalTests;
Rules of Promotion
2. Use a double literal for one of the values on the right
hand side
double average = (90.0+92+95+100) / 4;
3. Use a Cast Operator
int totalTests = 4;
double average = (90+92+95+100)/(double)totalTests;
In this case, totalTests is explicitly cast to a double. And, because we
have one double, everything else is promoted. Note that you can also
use the (int) cast to cast a double to an integer.
constants
final int TOTAL_GRADES
= 4;
• Used to avoid “magic numbers” in code.
– Only need to change in one place
• If not, best case must search entire code, worst case you miss a
few occurrences.
– Choose meaningful names for your constants as you would
for any other identifier
• Unlike variables, you cannot change the value of a
symbolic constant.
• Should be in ALL CAPS (style).
more on casting
• In an assignment statement, you can assign a value
of a “less expressive” type to a variable which is
“more expressive”. For example:
– int gets byte
– double gets int
– double gets float
• You must explicitly cast a value of a “more
expressive” type to a variable which is “less
expressive”. For example:
–
–
–
–
byte gets (byte) int
int gets (int) double
float gets (float) double
If you do not explicitly cast these values, you will have a
syntax error in Java.
Warning about floating point values
• Floats may be represented differently from what
you think by the computer
– E.g. 1.9 to you may be 1.89999999999999999999999
– 1.9 will not necessarily equal 1.9!
• In critical calculations for the same reason
– E.g. .1 added 10 times often will not add up to 1
– Use long integers instead and keep track of where your
decimal point is (e.g. $1.75 should be stored as 175)
Road map
• char data type
• Reading
– Liang 5: Chapter 2: 2.7.4; 2.9;
– Liang 6: Chapter 2: 2.7.4; 2.9
– Liang 7: Chapter 2: 2.7.4; 2.9
Introduction to Computers and
Programming
Lecture 5
Boolean type; if statement
Professor: Evan Korth
New York University
Road Map
•
•
•
•
•
Review Div / Mod
Reverse digits of a number
boolean type
Algorithms
Representing programs
– Pseudocode
– Flow charts
• Control structures
– overview
– introduction to if statement
Reading
– Liang 5: Chapter 2: 2.10; Chapter 3: 3.1 – 3.2..2
– Liang 6 & 7: Chapter 3: 3.1 – 3.3
review
div mod worksheet
review
• Why do we use constants in our programs instead
of literal values?
• Is the following constant declaration good style?
final int total
= 5;
• Name 4 different numeric data types?
• Is there a difference between the way 4.0 (a double)
and 4 (an int) are represented by the computer?
• What does it mean to cast a value?
• When must you explicitly cast a value?
• If you mix numeric data types on the right hand
side of a gets operator, what happens?
Review
• What happens if you go beyond a type’s upper
bound?
– For example:
int i = 2147483647;
i = i + 1;
• What happens if you try to place a literal value in
an integer type that is too big for the variable?
– For example: byte b = 483648;
• What if you go beyond an integer type’s bounds
using arithmetic?
• Which has higher precedence:
– + (addition)
– % (modulus)
Boolean values
• Java provides a type just for true and false
evaluation.
• Named after George Boole, the English
mathematician who published “An investigation
into the Laws of Thought” in 1854 which began
Boolean logic.
• Any Boolean expression will evaluate to either
true or false.
Relational Operators
Operator
Meaning
>
Greater than
<
Less than
>=
<=
Greater than or equal
to
Less than or equal to
==
Equal to
!=
Not Equal to
2003 Prentice Hall, Inc. All rights reserved.
Example
import javax.swing.JOptionPane;
public class BoolTest
{
public static void main(String[] args)
{
boolean boolVar;
}
}
boolVar: false
boolVar = false;
System.out.println ("boolVar: " + boolVar);
boolVar: true
int a = 10;
int b = 10;
boolVar = ( a == b);
System.out.println ("boolVar: " + boolVar);
false
System.out.println (a == b);
System.out.println (a != b);
System.out.println (a < b);
System.out.println (a <= b);
System.out.println (a > b);
System.out.println (a >= b);
false
true
false
true
true
Equality v. Assignment
• Remember Gets not Equals!
( grade = 100 )
Will not evaluate to true or false
• In this case, we are using a single = character.
(We really want to use ==)
Introduction to Problem Solving with Computers
• Before writing a program:
– Have a thorough understanding of the problem
– Carefully plan an approach for solving it
• While writing a program:
– Know what “building blocks” are available
– Use good programming principles
Algorithms
• Computing problems
– All can be solved by executing a series of actions in a
specific order
• Algorithm: procedure in terms of
– Actions to be executed
– The order in which these actions are to be executed
• Program control
– Specify order in which statements are to executed
• Examples of problems:
– Determining the class average for a final exam
– Sorting a list of names in alphabetical order
2003 Prentice Hall, Inc. All rights reserved.
Pseudocode
• Pseudocode
– Artificial, informal language that helps us develop
algorithms
– Similar to everyday English
– Not actually executed on computers
– Helps us “think out” a program before writing it
• Easy to convert into a corresponding Java program
• Consists only of executable statements
– For example, declarations and import statements are not
used in pseudocode.
2000 Prentice Hall, Inc. All rights reserved.
What is a “Flow Chart?”
• A flow chart is a visual tool that helps you
understand the flow of your program.
– Graphical representation of program structure
• Different shapes have different meaning.
Flow Chart Basics 1
Connector
symbol
flow
line
Diamonds
(decision symbol)
contain
conditions
Rectangles represent
statements of work.
For example:
flow
line
System.out.println();
Control Structures
Control Structures
• Control the flow of a program
• Normally, in Java, statements are executed in
sequential order
• Control structures allow the programmer to
specify that a statement other than the next be
executed
– i.e. programmer can control what’s executed in which order
Three Basic Control Structures
• All programs can be written with just these types
of structures
– Sequence structure
• Statements run one after the other
– Selection structure
• Depending on a condition, do one thing; otherwise, do
something else
• Examples in Java: if, if else, and switch.
– Repetition structure
• Repeat some actions over and over
• Examples in Java: for loops, while loops, and do/while loops.
The if structure
• Pseudocode:
if some Boolean expression is true
do this
• Example:
if ( x == y )
{
System.out.println(" x is equal to y!" ) ;
}
• Every procedural / OO programming language has
some form of an if statement.
Another if example
if ( temperature >= 85 )
{
System.out.println( "It is hot out!" );
}
if Flow Chart
temperature >=85
false
true
print “It is hot”
if with a twist: if else
• Pseudocode:
if some Boolean expression is true
do this
otherwise
do something else
• Example:
if ( grade >= 65 )
System.out.println( "You passed!" );
else
System.out.println( "You failed!" );
if/else Flow Chart
False
True
grade
>=60
Print “You
failed”
Print “You
passed”
Blocks
• To run several lines of code together,
you must include them within a block
• For example:
if ( grade >= 60 )
{
System.out.println ( "You passed!" );
System.out.println ( "Congratulations!" );
}
Indentation
• Everything within the block of code (even if it is
an implicit block because we only use one
statement) should be indented
– helps you see the block at a quick glance.
• Avoid writing code like this:
if (grade >= 65) {
System.out.println("You passed!!!\n");
System.out.println ("Congratulations!\n");
}
• This is valid Java code, but it is not easy to view
the block: bad style
Common error: misplaced semi-colon
• Remember, Java requires that you use a semicolon
to terminate a statement.
• A complete if statement is formed as follows:
if (boolean expression)
Statement or block of code;
• Therefore, if you place a semicolon after the
conditional as in
if (boolean expression);
Statement or block of code;
The compiler will interpret the semicolon as a null statement. In other
words, nothing will happen if the expression evaluates to true and the
statement of block of code will be executed whether or not the boolean
expression is true.
Example
import javax.swing.JOptionPane;
public class PassFail
{
public static void main(String[] args)
{
int grade;
String gradeAsString;
gradeAsString = JOptionPane.showInputDialog(null,"What is your grade?");
grade = Integer.parseInt (gradeAsString);
/* find out if grade is passing */
if ( grade >= 65 )
{
System.out.println ( "You passed!!!" );
System.out.println ( "Congratulations!" );
}
else
{
System.out.println ("You failed!");
}
System.exit (0);
}
}
Introduction to Computers and
Programming
Lecture 6
Professor: Evan Korth
New York University
Road Map
• if / else continued
– Nested if / else statements
• Logical operators
– &&, ||, ^
– !
– &, |
• switch statement
• Reading:
– Liang 5: chapter 2: 2.10;chapter 3: 3.2
– Liang 6: chapter 3: 3.3 - 3.5
– Liang 7: chapter 3: 3.3 - 3.5
review
• What is the output of the following code
fragment?
int a = 100;
if (a = 100)
System.out.println (" a is equal to " + a);
• What is the output of the following code
fragment?
int a = 100, b = 1;
if (a < b)
System.out.println ("a is less than b");
review
• What is the output of the following code
fragment?
int a = 100;
if (a != 100);
System.out.println (" a is equal to " + a);
• What is the output of the following code
fragment?
int a = 100, b = 1;
if (a < b)
System.out.println ("a is less than b");
System.out.println ("Thank you");
Java Provides a shortcut if/else operator:
• This is Java’s only ternary operator (i.e. it takes three operands)
System.out.println ( (sales > 100) ? "Federal Express" : "US Mail");
The
conditional ? shortTrue
Statement. cut operator Option
colo
n
False
Option
nested if statements
• When one if/else structure is contained
inside another if/else structure it is called
a nested if/else.
if (grade > 60)
{
if (grade > 70)
System.out.println("You passed");
else
System.out.println("You passed but need a tutor");
}
else
System.out.println("You failed");
else if
• Usually you try to nest within the else statement. Note
the indentation.
if (grade > 70)
System.out.println("You passed");
else if (grade > 60)
System.out.println("You passed but need a tutor");
else
System.out.println("You failed");
Choosing the flavor of your if
•
When you have multiple possible branches, you
can have any of the following situations:
1. You want to execute exactly one of the branches
2. You want to execute zero or one of the branches
3. You want to execute zero or more branches
•
1–c
2–b
Which would be appropriate for each of the
3–a
situations above:
a) A series of ifs
b) A series of if / else ifs ending with an else if
c) A series of if / else ifs ending with an else
Using boolean variables as flags
• You may want to use boolean variables to hold the
value of a boolean expression.
• For example:
boolean passed = (grade >= 65)
• Then you can use the variable later in a
conditional statement:
if (passed)
System.out.println ("You passed");
else
System.out.println ("You failed");
&& - Logical AND
((boolean exp a) && (boolean exp b))
• When using the and operator (&&), both
expression a and b must be true for the compound
statement to be true.
truth table
F A LS E
TR U E
F A LS E
F A LS E
F A LS E
TR U E
F A LS E
TR U E
• For example:
((total > 50) && (status == 0))
|| - Logical OR
((boolean exp a) || (boolean exp b))
• When using the or operator (||), at least one
expression a or b must be true for the compound
statement to be true.
truth table
F A LS E
TR U E
•
F A LS E
F A LS E
TR U E
TR U E
TR U E
TR U E
For example:
((total > 50) || (status == 0))
^ - Exclusive OR
((boolean exp a) ^ (boolean exp b))
• When using the exclusive or operator (^), at least
one expression a or b must have opposite Boolean
values for the compound statement to be true.
truth table
FALSE
TRUE
•
FALSE
FALSE
TRUE
TRUE
TRUE
FALSE
For example:
((person1 == 1) ^ (person2 == 1))
logical negation !
!(a)
• Reverses the truth or falsity of expression a
Boolean expression
• ! has high precedence so you must use parenthesis
• You can avoid using the logical negation by
expressing the condition differently with an
appropriate relational operator. However, in the
case of complex expressions, it is sometimes
easier to use negation.
• Note: its a unary operator
Unconditional vs. Conditional Boolean
Operators
• Java provides us with a second “and” operator and
a second “or” operator.
• The unconditional operators guarantee that both
expressions will be evaluated
• In this class, you should just use the conditional
operators.
switch Multiple-Selection Structure
• Used when testing a variable or expression for
EQUALITY (ie no >, <, >=, <= tests) separately
for each of the constant integral values it may
assume.
• Preferred over if else in situations where you are
testing the same expressions for equality with
many different values.
• Allows you to perform different actions for each
value.
switch Multiple-Selection Structure
switch (expression) {
case value1:
action(s);
break;
keyword switch
expression can be a variable or
a more complicated expression
case value2:
action(s);
break;
…
default:
actions(s);
break;
}
could use more than one case;
if the same actions are required
actions within a single case do
not need brackets
the default case will be executed
in the event that no other case is
The switch Multiple-Selection Structure
• Flowchart of the switch structure
case a
true
case a action(s)
break
false
case b
true
case b action(s)
break
false
.
.
.
case z
true
case z action(s)
break
false
default action(s)
2000 Prentice Hall, Inc.
All rights reserved.
beware of “fall through”
• If you forget to use the break keyword between
cases, unexpected things may happen.
• Once a case tests true, all the statements following
that case, will be executed until the next break.
• Experienced programmers may use this on
purpose. For this class we will rarely use fall
though.
Style Considerations
Initialization (revisited)
• When you declare a primitive variable, you do not
know the value stored in that variable until you
place something there. The language specification
does not guarantee any initial value.
• Until the user initializes the value, the value stored
in that memory is called a garbage value.
• Java will not allow you to use the garbage value in
a calculation or for output. If it is possible that a
variable has not been initialized when you try to
use it, you will get a compilation error.
• So you must initialize the variable before you use
it on the right hand side of a calculation or output
it to the screen.
Principle of Proximity
• Advanced tip for initialization
• Initialize your variables close to where you use
them if possible
– Avoid mistakes about value when using late in code
(something modified it?)
Line Continuations
• Pick good spots to break up a long line
– Break so it’s obvious from reading a line there should be more
• E.g.
if ( (totalSaleBeforeTax > 100) &&
(isPreferredCustomer) )
System.out.print("");
– Note, the dangling && should alert reader to a break
Braces
• Whenever adding a left brace to denote a block or
method start, add the right brace right away and
then fill between them
• Put a comment after the right brace!
if ( MyGrade < YourGrade )
{
} /* end if (MyGrade < YourGrade) */
else
{
} /* end else of (MyGrade < YourGrade) */
} /* end program */
• Use curly braces even if you only have one
statement as the body of a control structure.
indentation
• Place the brace associated with a control
statement (or method / class header) on the next
line, indented to the same level as the control
statement.
• Statements within the braces are indented to the
next level.
• For example:
public class
{
public static void main…
…
}
HW submissions
• For this class you should have a comment like the
following:
/**********************************
* [GENERAL INTRODUCTION WITH THE
* TITLE OF YOUR PROGRAM]
* Written by [YOUR NAME]
* Date: [MONTH DAY, YEAR]
* NYU ID: [YOUR N-NUMBER]
**********************************/
• Outside of class you should also have a similar
comment describing your .java file.
Introduction to Computers and
Programming
Lecture 7: assignment operators
and introduction to while loops
Instructor: Evan Korth
New York University
Road map
• char data type
• Assignment operators
• Introduction to while loops
• Reading
– Liang 5: Chapter 2: 2.7.4; 2.9; Chapter 3: 3.3, 3.3.1
– Liang 6: Chapter 2: 2.7.4; 2.9; Chapter 4.1, 4.2 (part)
– Liang 7: Chapter 2: 2.7.4; 2.9; Chapter 4.1, 4.2 (part)
Review
• True or False: An int variable can contain any
integer.
• When must you use an if / else if /
else statement instead of using a switch
statement?
• When is it preferable to use a switch statement?
• What is a magic number? How should you deal
with a magic number? Why?
• Explain what the exclusive or (^) operator tests.
(exp a) ^ (exp b)
• Define the purpose of each part of this expression:
(part a) ? (part b) : (part c)
Review continued
• What is the output of the following code
fragment?
int a = 100, b = 50;
if ((a == 60) && (b <= 100))
System.out.println ("Yes");
• What is the output of the following code
fragment?
int a = 100, b = 50;
if ((a == 60) || (b <= 100))
System.out.println ("Yes");
Review continued
• What is the output of this switch statement?
int a = 90;
switch (a)
{
case 80:
System.out.println (80);
case 90:
System.out.println (90);
case 100:
System.out.println (100);
}
char data type
char data type
•
•
•
•
•
•
•
•
Java allows us to store "single" character values.
char character = 'a'; // not the same as "a";
char character = '7';
char newline = '\n';
char tab = '\t';
char space = ' ';
The characters are actually stored as integers (ascii values).
See http://asciitable.com/
• Note: chars use single quotes. We have seen that
Strings use double quotes.
ASCII Table
Source: Liang
char arithmetic
• Given:
char letter = 'a';
• The following code:
letter = (char) (letter + 1);
• Would result in letter storing a 'b' character.
• If we add or subtract two char values, the result is
an int value.
– For example 'c' – 'a' would result in the value 2.
Reading char values from the user
• You should use charAt(0) to parse the
character from user input.
• For example:
char c;
String cAsString;
cAsString = JOptionPane.showInputDialog
(null, "Enter a character");
c = cAsString.charAt(0);
• Will grab the first character from the user's input.
Casting between char and int values
• A char uses 16 bits of memory.
– You can implicitly cast a char to an int
char c = 'a';
int i = c;
– You must explicitly cast an int to a char
int i = 65;
char = (char) i;
• Note: Even though chars are equal to shorts in the
amount of memory they use, they do not hold the
same values (shorts can hold negative integers).
Warning about numeric digit characters
• The value of a the single digit numeric characters
are not equivalent to the values themselves. In
fact the ASCII value of '0' is 48, '1' is 49, …, '9' is
57.
• How do you think we could convert a numeric
char to an int?
Unicode
• In Java, there are many more characters available then in
the basic ascii table.
• The ascii table only has 128 characters in it.
• Java uses 2 bytes to store characters which allows it to
hold 65536 unique characters.
• Java can store any Unicode (see: unicode.org) character in
a char variable.
• That means you can print any character from any language
on any platform.
• To print a Unicode character, use '\uxxxx' where xxxx is a
hexadecimal representation of the Unicode for the desired
character.
Assignment Operators
• Given the following:
x = 2;
x = x + 1;
System.out.println ("x: " + x);
• There are actually several ways to rewrite this
more concisely.
Short Cut Operator
• One option is to use the += operator
x = 2;
x += 1; // same as x = x + 1;
System.out.println ("x: " + x);
• There are similar operators for *, -, /.%
–
–
–
–
x
x
x
x
=
=
=
=
x
x
x
x
*
–
/
%
5
5;
5;
5;
is
is
is
is
equivalent
equivalent
equivalent
equivalent
to
to
to
to
x
x
x
x
*=
-=
/=
%=
5;
5;
5;
5;
• Good Practice: place a space before and after your
short cut operators.
Increment Operator
• A second option is to use an increment operator:
x++
Post-Increment Operator
++x
Pre-Increment Operator
• Both operators will increment x by 1, but they do
have subtle differences.
Pre v. Post Increment
• PostIncrement Operator (x++):
– use the current value of x in the expression.
Then, increment by 1.
• PreIncrement Operator (++x):
– Increment x by 1. Then, use the new value of x
in the expression.
How about a real example?
// Preincrementing v. PostIncrementing
public class PrePost
{
public static void main (String[] args)
{
Post Increment
int c = 5;
Output:
System.out.println (c);
5
System.out.println (c++);
System.out.println (c);
5
System.out.println();
6
c = 5;
System.out.println (c);
System.out.println (++c);
5
System.out.println (c);
6
}
}
Pre Increment
2000 Prentice Hall, Inc. All rights reserved.
6
Modified by Evan Korth
Pre v. Post Decrement
• PostDecrement Operator (x--):
– use the current value of x in the expression.
Then, decrease by 1.
• PreDecrement Operator (--x):
– Decrease x by 1. Then, use the new value of x
in the expression.
• Good practice: Place unary operators
directly next to their operands, with no
intervening spaces.
Introduction to While Loops
While Loops
• While Loop: Keep repeating an action while some
condition remains true.
• Examples:
– Every Stairmaster Machine contains a while
loop (end condition is based on mode used).
• while the person is still climbing, keep
displaying the status, e.g. number of stairs
climbed, calories burned, etc.
– Keep prompting for book orders until the user
is done.
while loop (continued)
• For example (in pseudocode)
while (some Boolean expression is true)
{
do this (again and again...)
}
Parts of a While Loop
•
Every while loop will always contain three main
elements:
1) Priming: initialize your variables.
2) Testing: test against some known condition.
3) Updating: updates part (or all) of the
expression that is tested.
Simple While Loop
public class While1
{
public static void main (String args[])
{
1. Priming
int index = 1;
while (index <= 10)
2. Test Condition
{
System.out.println ("Index: " + index);
index++;
Index: 1
3. Update: In this
}
Index: 2
case, you can use
}
either the pre or post
Index: 3
}
increment operator.
...
Index:
8
Index:
9
Index:
10
While Loop Flowchart
1. Priming
Set index=1
2. Test
index
<= 10
FALSE
TRUE
3. Print value of
index
Update index++
Infinite Loop
• Infinite Loop: A loop that never ends.
– Generally, you want to avoid these!
– There are special cases, however, when you do
want to create infinite loops on purpose.
• Common Exam Questions:
– Given a piece of code, identify the bug in the
code.
– You may need to identify infinite loops.
Infinite Loop Example #1
public class While2
{
public static void main (String args[])
{
int index = 1;
while (index <= 10)
{
System.out.println ("Index: " + index);
}
Index:
}
Index:
}
Here, I have deleted part 3:
The update statement (index++).
1
1
Index:
1
Index:
1
Index:
1
…
[forever]
Infinite Loop, Example #2
public class While3
{
public static void main (String args[])
{
int index = 1;
while (index >= 0)
{
System.out.println ("Index: " + index);
index++;
Index:
}
Here, I have changed Index:
}
Index:
}
Part 2: the test
condition.
1
2
3
Index:
4
Index:
5
…
[forever]
While Loops: Examples
While Loop Example
• Specification for the program:
– Find the first power of 2 larger than 1000.
• For example: 2, 4, 8, 16, 32, etc. are powers of 2.
– Which is the first power of 2 larger than 1000?
– Finding the answer to this requires some kind of a while
loop.
– Let’s see how…
2000 Prentice Hall, Inc. All rights reserved.
Modified by Evan Korth
While Loop Example
• Example:
int product = 2;
while ( product <= 1000 )
product = 2 * product;
product <= 1000
false
2000 Prentice Hall, Inc. All rights reserved.
true
product = 2 * product
public class PowerOfTwoOver1000
{
public static void main (String args[])
{
int product = 2;
while ( product <= 1000 )
product = 2 * product;
System.out.println (product);
}
}
2000 Prentice Hall, Inc. All rights reserved.
Counter-Controlled Repetition
• Counter-controlled repetition
– Loop repeated until counter reaches a certain value
– Definite repetition: number of repetitions is known
– Example: A class of ten students took a quiz. The grades
(integers in the range 0 to 100) for this quiz are available to
you. Determine the class average on the quiz
2000 Prentice Hall, Inc. All rights reserved.
4.8
Formulating Algorithms: Case Study 1
(Counter-Controlled Repetition)
• Counter
– Variable that controls number of times set of statements
executes
• Average1.java calculates grade averages
– uses counters to control repetition
2003 Prentice Hall, Inc. All rights reserved.
Set total to zero
Set grade counter to one
While grade counter is less than or equal to ten
Input the next grade
Add the grade into the total
Add one to the grade counter
Set the class average to the total divided by ten
Print the class average
Fig. 4.6 Pseudocode algorithm that uses countercontrolled repetition to solve the class-average
problem.
2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Fig. 4.7: Average1.java
// Class-average program with counter-controlled repetition.
import javax.swing.JOptionPane;
public class Average1 {
public
{
int
int
int
int
static void main( String args[] )
total;
gradeCounter;
grade;
average;
//
//
//
//
sum of grades input by user
number of grade to be entered next
grade value
average of grades
String gradeString; // grade typed by user
// initialization phase
total = 0;
// initialize total
gradeCounter = 1;
// initialize loop counter
// processing phase
while ( gradeCounter <= 10 ) {
// loop 10 times
// prompt for input and read grade from user
gradeString = JOptionPane.showInputDialog(
"Enter integer grade: " );
// convert gradeString to int
grade = Integer.parseInt( gradeString );
2003 Prentice Hall, Inc. All rights reserved.
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
total = total + grade;
gradeCounter = gradeCounter + 1;
// add grade to total
// increment counter
} // end while
// termination phase
average = total / 10;
// integer division
// display average of exam grades
JOptionPane.showMessageDialog( null, "Class average is " +
average, Class Average", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
// terminate the program
} // end main
} // end class Average1
2003 Prentice Hall, Inc. All rights reserved.
Introduction to Computers and
Programming
Lecture 8: More Loops
Professor: Evan Korth
New York University
Road Map
•
•
•
•
•
•
Sentinels
Sentinel Controlled Loops
Case Study: Sentinel Controlled Loop
Case Study: Nested Control Structures
do/while Loop
Summary of looping covered so far
• Reading
– Liang 5:chapter 3: 3.3.1, 3.3.2
– Liang 6: chapter 4: 4.2, 4.3
– Liang 7: chapter 4: 4.2, 4.3
review
• What are three ways to rewrite:
x = x + 1;
• What are the three elements of a while loop?
• What is the difference between pre and post
increment operators?
• Are you guaranteed to execute the body of a while
loop at all?
• What is an infinite loop?
• True or False: You never want to use an infinite
loop?
Review
• Given:
char c = 'a';
c++;
What is the value of variable c?
• What method do you use to extract characters
from a String?
– How would you use that method to get the first character
from a String?
• How are characters stored in memory?
• What is the difference between the character '0'
and the integer 0?
Sentinels
Sentinel-controlled repetition
• Counter Controlled Repetition:
– Simply means that we use a counter to tell you when to stop
repeating a statement or group of statements
– The examples from last class were counter-controlled
repetition
• However, what if we want the user or the input to
decide when to end the program?
– Use a sentinel
Understanding Sentinels
• Sentinel: a special value that indicates the “end of
data entry.”
• Also known as signal value, dummy value, or flag
value
• For example:
–
–
–
–
-1 means end of data.
0 means end of data.
"END" means ends of data
Depends on the specific application you are building.
• With a sentinel, we have an indefinite repetition,
because the number of repetitions is unknown at
the time we write the program (or start the loop).
2000 Prentice Hall, Inc. All rights reserved.
Modified by Evan Korth
Using Sentinels
• How are they used?
– Programmer picks a value that would never be encountered
for normal data
– User enters normal data and then when done, enters the
sentinel value
– The loop will stop when seeing the sentinel value
Using Sentinels cont’d
• For example, if entering age for people, could pick
a sentinel of –1
• No one would expect to be –1 year old.
• Good practice is to remind the user in each
iteration of the loop what the sentinel value is
– For example,
System.out.println
(" Enter age of current resident or –1 to end" );
/*
A sentinel controlled loop */
/*
A simple census taker */
import javax.swing.JOptionPane;
public class Sentinel
{
public static void main(String [] args)
{
int currentAge = 0 ;
String currentAgeAsString;
/*
priming */
currentAgeAsString = JOptionPane.showInputDialog ("Enter age of resident:
") ;
currentAge = Integer.parseInt (currentAgeAsString);
/* testing:
keep going until input is sentinel value */
while (currentAge != -1)
{
/* do some calculations with age, e.g. AVERAGE */
/*updating: get the next value from the user */
currentAgeAsString = JOptionPane.showInputDialog ("Enter age of resident:
currentAge = Integer.parseInt (currentAgeAsString);
}
System.exit (0);
}
}
") ;
Good Programming tips
• Pick a sentinel value that you are CERTAIN will
never be confused with normal data
• Style: Remind user each iteration what the sentinel
is
• Y2K-like problem
– Programmers often used 9999 as a sentinel to end a loop
– Worry that on September 9, 1999 (sometimes abbreviated
9999) programs would erroneously stop executing before
they were supposed to.
Case Study: Using Sentinel
Controlled Loops
Formulating Algorithms with Top-Down,
Stepwise Refinement
• Problem becomes:
Develop a class-averaging program that will process an
arbitrary number of grades each time the program is run.
– Unknown number of students
– How will the program know to end?
• Use sentinel value
– Loop ends when user inputs the sentinel value
– Sentinel value chosen so it cannot be confused with a regular
input (such as -1 in this case)
2000 Prentice Hall, Inc. All rights reserved.
Formulating Algorithms with Top-Down,
Stepwise Refinement
• Top-down, stepwise refinement
– Begin with a pseudocode representation of the top:
Determine the class average for the quiz
– Divide top into smaller tasks and list them in order:
Initialize variables
Input, sum and count the quiz grades
Calculate and print the class average
• Many programs have three phases:
– Initialization: initializes the program variables
– Processing: inputs data values and adjusts program variables
accordingly
– Termination: calculates and prints the final results
2000 Prentice Hall, Inc. All rights reserved.
Formulating Algorithms with Top-Down,
Stepwise Refinement
• Refine the initialization phase from Initialize
variables to:
Initialize total to zero
Initialize counter to zero
• Refine Input, sum and count the quiz grades to
Input the first grade (possibly the sentinel)
While the user has not as yet entered the sentinel
Add this grade into the running total
Add one to the grade counter
Input the next grade (possibly the sentinel)
2000 Prentice Hall, Inc. All rights reserved.
Formulating Algorithms with Top-Down,
Stepwise Refinement
• Refine Calculate and print the class average to
If the counter is not equal to zero
Set the average to the total divided by the counter
Print the average
else
Print “No grades were entered”
2000 Prentice Hall, Inc. All rights reserved.
Initialize total to zero
Initialize counter to zero
Input the first grade (possibly the sentinel)
While the user has not as yet entered the sentinel
Add this grade into the running total
Add one to the grade counter
Input the next grade (possibly the sentinel)
If the counter is not equal to zero
Set the average to the total divided by the counter
Print the average
else
Print “No grades were entered”
Fig. 4.8 Class-average problem pseudocode
algorithm with sentinel-controlled repetition.
2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Fig. 4.9: Average2.java
// Class-average program with sentinel-controlled repetition.
import java.text.DecimalFormat; // class to format numbers
import javax.swing.JOptionPane;
Outline
Average2.java
public class Average2 {
public static void main( String args[] )
{
int total;
// sum of grades
int gradeCounter;
// number of grades entered
int grade;
// grade value
double average;
// number with decimal point for average
String gradeString;
// grade typed by user
// initialization phase
total = 0;
// initialize total
gradeCounter = 0; // initialize loop counter
// processing phase
// get first grade from user
gradeString = JOptionPane.showInputDialog(
"Enter Integer Grade or -1 to Quit:" );
// convert gradeString to int
grade = Integer.parseInt( gradeString );
2003 Prentice Hall, Inc.
All rights reserved.
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// loop until sentinel value read from user
while ( grade != -1 ) {
loop//until
total = total + grade;
add gradeCounter
grade to total
gradeCounter = gradeCounter + 1;equals
// increment
counter
sentinel value
(-1)
// get next grade from user
gradeString = JOptionPane.showInputDialog(
"Enter Integer Grade or -1 to Quit:" );
// convert gradeString to int
grade = Integer.parseInt( gradeString );
Outline
Average2.java
Line 31
Line 45
} // end while
// termination phase
// if user entered at least one grade...
if ( gradeCounter != 0 ) {
// calculate average of all grades entered
average = (double) total / gradeCounter;
// display average with two digits of precision
JOptionPane.showMessageDialog( null,
"Class average is " + average ,
"Class Average", JOptionPane.INFORMATION_MESSAGE );
} // end if part of if...else
2003 Prentice Hall, Inc.
All rights reserved.
60
61
62
63
64
65
66
67
68
else // if no grades entered, output appropriate message
JOptionPane.showMessageDialog( null, "No grades were entered",
"Class Average", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
// terminate application
Outline
Average2.java
} // end main
} // end class Average2
2003 Prentice Hall, Inc.
All rights reserved.
Case Study: Nested Control
Structures
Nested control structures
• Problem
– A college has a list of test results (1 = pass, 2 = fail) for 10
students
– Write a program that analyzes the results
• If more than 8 students pass, print "Raise Tuition"
• Notice that
– The program must process 10 test results
• Counter-controlled loop will be used
– Two counters can be used
• One for number of passes, one for number of fails
– Each test result is a number—either a 1 or a 2
• If the number is not a 1, we assume that it is a 2
2003 Prentice Hall, Inc. All rights reserved.
Nested control structures
• Top level outline
Analyze exam results and decide if tuition should be raised
• First Refinement
Initialize variables
Input the ten quiz grades and count passes and failures
Print a summary of the exam results and decide if tuition should
be raised
• Refine Initialize variables to
Initialize passes to zero
Initialize failures to zero
Initialize student counter to one
2003 Prentice Hall, Inc. All rights reserved.
Nested control structures
• Refine Input the ten quiz grades and count passes
and failures to
While student counter is less than or equal to ten
Input the next exam result
If the student passed
Add one to passes
else
Add one to failures
Add one to student counter
• Refine Print a summary of the exam results and
decide if tuition should be raised to
Print the number of passes
Print the number of failures
If more than eight students passed
Print “Raise tuition”
2003 Prentice Hall, Inc. All rights reserved.
Initialize passes to zero
Initialize failures to zero
Initialize student to one
While student counter is less than or equal to ten
Input the next exam result
If the student passed
Add one to passes
else
Add one to failures
Add one to student counter
Print the number of passes
Print the number of failures
If more than eight students passed
Print “Raise tuition”
Fig 4.10 Pseudocode for examination-results problem.
2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Fig. 4.11: Analysis.java
// Analysis of examination results.
import javax.swing.JOptionPane;
public class Analysis {
Outline
Loop until student counter is
greater than 10
Analysis.java
Line 19
public static void main( String args[] )
{
// initializing variables in declarations
int passes = 0;
// number of passes
int failures = 0;
// number of failures
int studentCounter = 1; // student counter
int result;
// one exam result
String input;
String output;
// user-entered Nested
value
// output string
Line 29
control structure
// process 10 students using counter-controlled loop
while ( studentCounter <= 10 ) {
// prompt user for input and obtain value from user
input = JOptionPane.showInputDialog(
"Enter result (1 = pass, 2 = fail)" );
// convert result to int
result = Integer.parseInt( input );
// if result 1, increment passes; if...else nested in while
if ( result == 1 )
passes = passes + 1;
2003 Prentice Hall, Inc.
All rights reserved.
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
else // if result not 1, increment failures
failures = failures + 1;
// increment studentCounter so loop eventually terminates
studentCounter = studentCounter + 1;
Outline
Analysis.java
} // end while
// termination phase; prepare and display results
output = "Passed: " + passes + "\nFailed: " + failures;
// determine whether more than 8 students passed
if ( passes > 8 )
output = output + "\nRaise Tuition";
JOptionPane.showMessageDialog( null, output,
"Analysis of Examination Results",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
// terminate application
} // end main
} // end class Analysis
2003 Prentice Hall, Inc.
All rights reserved.
do/while Loop
The do/while Repetition Structure
• The do/while repetition structure
– Similar to the while structure
– Condition for repetition tested after the body of the loop is
performed
• All actions are performed at least once
– Format:
do {
statement(s);
} while ( condition );
4.8
The do/while Repetition Structure
• Flowchart of the do/while repetition structure
action(s)
true
condition
false
public class DoWhileTest
{
public static void main(String args[])
{
int counter;
counter = 1;
do
{
System.out.println ("counter: "+ counter);
counter ++;
} while (counter <= 10);
}
}
Common Errors
• In general you should avoid using floating point
types as control variables
– Why?
• Using a semi-colon after the while statement
• One off errors
Summary of Looping so far
Summary of Looping
• Two broad types of loops:
– Counter-controlled repetition
• A counter controls the number of repetitions.
• Also known as a definite repetition, because we know in
advance how many times the loop will be executed.
– Sentinel-controlled repetition
• A sentinel controls the number of repetitions
• Also known as indefinite repetition, because we do not know
in advance how many times the loop will be executed.
• In either case, watch out for infinite loops!
• If your program requires some kind of loop, first
determine which kind of loop you want.
Summary of Looping
• Once you know which kind of loop you want,
determine which while loop you want:
– While loops
• condition is tested first; then action occurs.
• While loops are much more common than do/while loops.
– Do/while loops
• action is run first; then, condition is tested.
• Use this if you want to make sure that your loop is guaranteed
to be run at least once.
Introduction to Computers and
Programming
Lecture 9: For Loops
Professor: Evan Korth
New York University
Road map
• Introduction to for loops
• Good practice and style using for loops
• Reading:
– Liang 5: Chapter 3: 3.3.3 (up to nested for loops)
– Liang 6: Chapter 4: 4.4, 4.5
– Liang 7: Chapter 4 : 4.4, 4.5
review
• What is the difference between a while and a do /
while loop?
• What is a sentinel value?
• How do you pick a good sentinel value?
• Would you ever intentionally want an infinite
loop?
• Why shouldn’t you generally use floats or doubles
as control variables in loops?
• What are the two possible values of a Boolean
variable?
For Loops
Parts of a Loop (reminder)
•
Every loop will always contain three main
elements:
– Priming: initialize your variables.
– Testing: test against some known condition.
– Updating: update the variable that is tested.
Loop types (reminder)
• Indefinite Loop:
– You do not know ahead of time how many times your loop
will execute.
– For example, you do not know how many books a person
might order.
• Definite Loop:
– You know exactly how many times you want the loop to
execute.
– not at compile time necessarily
For loops
• Another type of loop in Java is the for loop.
• It is very good for definite loops
• All the parts (priming, testing and updating) are in
one place.
• format:
for (prime expression; test expression; update expression)
• Since the expressions are all in one place, many
people prefer for to while when the number of
iterations is known.
Basic For Loop Syntax
• for loops are good for creating definite
loops.
int counter;
1. Priming: Set
the start value.
2. Test Condition:
Set the stop value.
3. Update: Update the
value.
for (counter =1;counter <= 10;counter++)
System.out.println (counter);
Note that each section is
separated by a semicolon.
for Loop Flowchart
1: Priming
Set counter=1
2: Test
counter
<= 10
FALSE
TRUE
Body: print counter
3: Update counter++;
Infinite Loop
• You can still end up with an infinite loop when
using for loops
for (counter = 0; counter <= 10; counter--)
For Loop Variations
• The limit can be a variable:
for ( i = 1; i <= limit; i++)
– This counts from 1 to limit
• Update may be negative:
for (i = 100; i >= 1; i--)
– This counts from 100 to 1.
• Update may be greater than 1:
for (i = 100; i >= 5; i -= 5)
– This counts from 100 to 5 in steps of 5
The for Structure: Notes and Observations
• Arithmetic expressions
– Initialization, loop-continuation, and increment can contain
arithmetic expressions. If x equals 2 and y equals 10
for ( j = x; j <= 4 * x * y; j += y / x )
is equivalent to
for ( j = 2; j <= 80; j += 5 )
• Notes about the for structure:
– If the loop continuation condition is initially false
• The body of the for structure is not performed
• Control proceeds with the next statement after the for structure
– Control variable
• Often printed or used inside for body, but not necessary
2000 Prentice Hall, Inc.
All rights reserved.
The Comma Operator
• Commas known here as comma operators
• by using commas, you can put more than one
statement in priming or updating expression
for (i = 100, y = 0; i >= 1; i--)
or
for (i = 1;
{
code;
}
j + i <= 10; i++, j++)
• Commas known here as comma operators
2000 Prentice Hall, Inc.
All rights reserved.
Modified by Evan Korth
Warnings
• Do not use a float or double for the counter
– May result in imprecise counter values and faulty evaluation
for loop termination purposes
• Don’t use commas instead of semicolons to
separate the components of the for loop
– (very common error)
• As in the if and while, do not put a semicolon ;
right after the parentheses – will be an empty
loop!
Off-by-one error
• In the first example, shown here, the following
counter < 10
would execute 9 times, not the desired 10 times
for (counter = 1; counter <= 10; counter++)
{
System.out.println (counter);
}/*
end for counter */
Help avoid off-by-one errors
• Try to make your conditions in the form <= not <
– Avoid code like counter < 11 or counter < 10
• There are times when we will break this rule
– arrays
– Strings
Good Programming Practices
• Do not change the value of the counter variable in your
loop.
– Do not attempt to manually adjust it to force an exit
– Can cause subtle errors that are difficult to catch
– Instead change your logic
• Do not put other expressions in the for control structure
– Manipulations of other variables should appear before or within
the body of the loop depending on whether or not you want to
repeat them
• Put a blank line before and after each major control
structure
• Try to limit nesting to three levels, if possible
– More than three levels of indentation can get confusing
• Limit the for control header to one line if possible
Problem
• Write a program which prompts the user for a
series of grades. After the user enters all the
grades, output the highest score. You do not know
beforehand how many grades the user will enter
(indefinite loop).
Introduction to Computers and
Programming
Lecture 10: For Loops
Professor: Evan Korth
New York University
review
•
•
•
•
What are the three parts of every loop?
Where are these three parts in a for loop?
Where are these three parts in a while loop?
Which two parts of the for loop will always be
executed?
• True or False: You must know at compile time
how many iterations you want to execute when
using a for loop?
Road map
• break
• continue
• Reading:
– Liang 6: Chapter 4: 4.9
– Liang 7: Chapter 4: 4.9
Nested For Loops
• It is also possible to place a for
loop inside another for loop.
Outer Loop
int rows, columns;
Output:
**********
**********
**********
**********
for (rows = 1; rows <= 5; rows++)
**********
{
for (columns=1; columns<=10; columns++)
System.out.print ("*");
System.out.println ();
Inner Loop
}
Nested For Loops, Example #2
Output:
*
int rows, columns;
Outer Loop
**
***
****
for (rows=1; rows<=5; rows++)
*****
{
for (columns=1; columns<=rows; columns++)
Inner Loop System.out.print ("*");
System.out.println ();
}
break and continue
break;
We have seen the keyword break used in a switch
statement:
switch (userInput) {
case 1:
userInput++;
break;
}
You can also use break inside of a for, while or
do/while loop to immediately exit from the loop.
Example of break use
public class Break
{
public static void main (String [] args)
{
int x;
for ( x = 1 ; x <= 10; x++)
{
if (x == 5)
break;
System.out.println("The number is : " + x);
} /* end for x = 1... */
}
}
continue
Continue is a statement which can be used inside a
for, while or do/while loop in order to skip the rest
of the remaining code in the loop, and start the
next iteration.
Example of continue
public class Continue
{
public static void main (String [] args)
{
int x;
for ( x = 1 ; x <= 10; x++)
{
if (x == 5)
continue ;
System.out.println("The number is : " + x);
} /* end for x = 1... */
}
}
Java Keywords
Ja va Keyw ord s
abstract
assert
boolean
break
case
catch
char
class
default
do
double
else
final
finally float
for
implements import
instanceof int
long
native
new
package
protected public
return
short
strictfp
super
switch
synchronized
throw
throws
transient try
volatile
while
Keywords that are reserved, but not currently used
const
goto
Fig. 4.2 Ja va keyw o rd s.
2003 Prentice Hall, Inc. All rights reserved.
byte
continue
extends
if
interface
private
static
this
void
Problem
• Use a while loop with a sentinel to read in letter
grades of the form A, B, C, D, F. Convert the
grades to numerical equivalents, based on the
following table, then print out the average grade in
numerical form.
Letter
Num
A
4.0
B
3.0
C
2.0
D
1.0
F
0.0
Structured Programming:
Summary
Summary
• Sequence
– Statement follow one another
• Selection Structures
–
–
–
–
if
if/else
if/else if/else
switch
• Repetition Structures
– while
– do/while
– for