cpac java procedural fundamentals complete
TRANSCRIPT
Introduction To Computers and Programming
Lecture 2: Your first program
Professor: Evan KorthNew 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?
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.
2003 Prentice Hall, Inc. All rights reserved.
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.
Outline
Welcome1.java
Program Output
1 // Fig. 2.1: Welcome1.java2 // Text-printing program.3 4 public class Welcome1 { 5 6 // main method begins execution of Java application7 public static void main( String args[] )8 {9 System.out.println( "Welcome to Java Programming!" );10 11 } // end method main12 13 } // end class Welcome1Welcome to Java Programming!
2003 Prentice Hall, Inc. All rights reserved.
2.2 A First Program in Java: Printing a Line of Text
– 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 */
1 // Fig. 2.1: Welcome1.java
(modified by Evan Korth)
2003 Prentice Hall, Inc. All rights reserved.
2.2 A First Program in Java: Printing a Line of Text
– Another line of comments– Note: line numbers not part of program, added for reference
2 // Text-printing program.
3
– Blank line (style)
•Makes program more readable
•Blank lines, spaces, and tabs are white-space characters
–Ignored by compiler
(modified by Evan Korth)
2003 Prentice Hall, Inc. All rights reserved.
– 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
2.2 A Simple Program: Printing a Line of Text
4 public class Welcome1 {
(modified by Evan Korth)
2003 Prentice Hall, Inc. All rights reserved.
2.2 A Simple Program: Printing a Line of Text
– 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
4 public class Welcome1 {
(modified by Evan Korth)
2003 Prentice Hall, Inc. All rights reserved.
2.2 A Simple Program: Printing a Line of Text
– 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)
– Part of every Java application• Applications begin executing at main
– Parenthesis indicate main is a method– Java applications contain one or more methods
4 public class Welcome1 {
7 public static void main( String args[] )
(modified by Evan Korth)
2003 Prentice Hall, Inc. All rights reserved.
2.2 A Simple Program: Printing a Line of Text
• 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
– 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.
7 public static void main( String args[] )
8 {
(modified by Evan Korth)
2003 Prentice Hall, Inc. All rights reserved.
2.2 A Simple Program: Printing a Line of Text
– 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 ;
9 System.out.println( "Welcome to Java Programming!" );
(modified by Evan Korth)
2003 Prentice Hall, Inc. All rights reserved.
2.2 A Simple Program: Printing a Line of Text
– Ends method declaration
– Ends class declaration– Can add comments to keep track of ending braces– Remember, compiler ignores comments– Comments can start on same line after code
11 } // end method main
13 } // end class Welcome1
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
– Line 9 displays “Welcome to ” with cursor remaining on printed line
– Line 10 displays “Java Programming! ” on same line with cursor on next line
9 System.out.print( "Welcome to " ); 10 System.out.println( "Java Programming!" );
2003 Prentice Hall, Inc.All rights reserved.
Outline
Welcome2.java
1. Comments
2. Blank line
3. Begin class Welcome2
3.1 Method main
4. Method System.out.print
4.1 Method System.out.println
5. end main, Welcome2
Program OutputWelcome to Java Programming!
1 // Fig. 2.3: Welcome2.java2 // Printing a line of text with multiple statements.3 4 public class Welcome2 {5 6 // main method begins execution of Java application7 public static void main( String args[] )8 {9 System.out.print( "Welcome to " ); 10 System.out.println( "Java Programming!" );11 12 } // end method main13 14 } // end class Welcome2 System.out.print keeps the cursor on the
same line, so System.out.println continues on the same line.
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)
– 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!" );
9 System.out.println( "Welcome\nto\nJava\nProgramming!" );
2003 Prentice Hall, Inc.All rights reserved.
Outline
Welcome3.java
1. main
2. System.out.println (uses \n for new line)
Program Output
1 // Fig. 2.4: Welcome3.java2 // Printing multiple lines of text with a single statement.3 4 public class Welcome3 {5 6 // main method begins execution of Java application7 public static void main( String args[] )8 {9 System.out.println( "Welcome\nto\nJava\nProgramming!" );10 11 } // end method main12 13 } // end class Welcome3
WelcometoJavaProgramming!
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
Escape sequence
Description
\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 Some common escape sequences.
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.
Outline
Welcome4.java
1. import declaration
2. Class Welcome4
2.1 main
2.2 showMessageDialog
2.3 System.exit
Program Output
1 // Fig. 2.6: Welcome4.java
2 // Printing multiple lines in a dialog box
3 import javax.swing.JOptionPane; // import class JOptionPane
4
5 public class Welcome4 {
6 public static void main( String args] )
7 {
8 JOptionPane.showMessageDialog(
9 null, "Welcome\nto\nJava\nProgramming!" );
10
11 System.exit( 0 ); // terminate the program
12 }
1 // Fig. 2.6: Welcome4.java2 // Printing multiple lines in a dialog box.3 4 // Java packages 5 import javax.swing.JOptionPane; // program uses JOptionPane6 7 public class Welcome4 {8 9 // main method begins execution of Java application10 public static void main( String args[] )11 {12 JOptionPane.showMessageDialog( 13 null, "Welcome\nto\nJava\nProgramming!" );14 15 System.exit( 0 ); // terminate application with window16 17 } // end method main18 19 } // end class Welcome4
2003 Prentice Hall, Inc. All rights reserved.
2.4 Displaying Text in a Dialog Box
– Lines 1-2: comments as before
– Two groups of packages in Java API– Core packages
• Begin with java• Included with Java 2 Software Development Kit
– Extension packages• Begin with javax
– import declarations • Used by compiler to identify and locate classes used in Java
programs• Tells compiler to load class JOptionPane from
javax.swing package
4 // Java packages
5 import javax.swing.JOptionPane; // program uses OptionPane
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
– 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
12 JOptionPane.showMessageDialog( 13 null, "Welcome\nto\nJava\nProgramming!" );
(modified by Evan Korth)
2003 Prentice Hall, Inc. All rights reserved.
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 Displaying Text in a Dialog Box
– 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
15 System.exit( 0 ); // terminate application with window
Introduction to Computers and Programming
Lecture 3: Variables and Input
Professor: Evan KorthNew 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 applicationpublic 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• 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.
balance
200
balance is a variablecontaining the value200, and can containonly 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;
data type identifier
semi-colon
2003 Prentice Hall, Inc. All rights reserved.
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.
(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[]) {
int x;int y;int z;
x = 5;y = 10;z = x + y;
System.out.println ("x: " + x);System.out.println ("y: " + y);System.out.println ("z: " + z);
} // end method main} // end class Sample
Variable Declarations
Data Type
Variable Name
Assignment Statements
x: 5y: 10z: 15
semicolon
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.
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.
2003 Prentice Hall, Inc. All rights reserved.
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.
Outline
Addition.java
1. import
2. class Addition
2.1 Declare variables (name and type)
3. showInputDialog
4. parseInt
5. Add numbers, put result in sum
1 // Fig. 2.9: Addition.java2 // Addition program that displays the sum of two numbers.3 4 // Java packages 5 import javax.swing.JOptionPane; // program uses JOptionPane6 7 public class Addition {8 9 // main method begins execution of Java application10 public static void main( String args[] )11 {12 String firstNumber; // first string entered by user 13 String secondNumber; // second string entered by user14 15 int number1; // first number to add 16 int number2; // second number to add 17 int sum; // sum of number1 and number218 19 // read in first number from user as a String 20 firstNumber = JOptionPane.showInputDialog( "Enter first integer" );21 22 // read in second number from user as a String 23 secondNumber = 24 JOptionPane.showInputDialog( "Enter second integer" );25 26 // convert numbers from type String to type int27 number1 = Integer.parseInt( firstNumber ); 28 number2 = Integer.parseInt( secondNumber ); 29 30 // add numbers 31 sum = number1 + number2;32
Declare variables: name and type.
Input first integer as a String, assign to firstNumber.
Add, place result in sum.
Convert strings to integers.
2003 Prentice Hall, Inc.All rights reserved.
Outline
Program output
33 // display result 34 JOptionPane.showMessageDialog( null, "The sum is " + sum,35 "Results", JOptionPane.PLAIN_MESSAGE ); 36 37 System.exit( 0 ); // terminate application with window38 39 } // end method main40 41 } // end class Addition
2003 Prentice Hall, Inc. All rights reserved.
2.5 Another Java Application: Adding Integers
– Location of JOptionPane for use in the program
– Begins public class Addition• Recall that file name must be Addition.java
– Lines 10-11: main
– Declaration• firstNumber and secondNumber are variables
5 import javax.swing.JOptionPane; // program uses JOptionPane
7 public class Addition {
12 String firstNumber; // first string entered by user 13 String secondNumber; // second string entered by user
2003 Prentice Hall, Inc. All rights reserved.
2.5 Another Java Application: Adding Integers
– 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 ;
– Can declare multiple variables of the same type at a time– Use comma separated list
– Can add comments to describe purpose of variables
String firstNumber, secondNumber;
12 String firstNumber; // first string entered by user 13 String secondNumber; // second string entered by user
2003 Prentice Hall, Inc. All rights reserved.
2.5 Another Java Application: Adding Integers
– 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
15 int number1; // first number to add 16 int number2; // second number to add 17 int sum; // sum of number1 and number2
2003 Prentice Hall, Inc. All rights reserved.
2.5 Another Java Application: Adding Integers
– 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
20 firstNumber = JOptionPane.showInputDialog( "Enter first integer" );
(modified by Evan Korth)
2003 Prentice Hall, Inc. All rights reserved.
2.5 Another Java Application: Adding Integers
– 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" )
20 firstNumber = JOptionPane.showInputDialog( "Enter first integer" );
2003 Prentice Hall, Inc. All rights reserved.
2.5 Another Java Application: Adding Integers
– Similar to previous statement• Assigns variable secondNumber to second integer input
– 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
23 secondNumber = 24 JOptionPane.showInputDialog( "Enter second integer" );
27 number1 = Integer.parseInt( firstNumber ); 28 number2 = Integer.parseInt( secondNumber );
(modified by Evan Korth)
2003 Prentice Hall, Inc. All rights reserved.
2.5 Another Java Application: Adding Integers
– 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
31 sum = number1 + number2;
2003 Prentice Hall, Inc. All rights reserved.
2.5 Another Java Application: Adding Integers
– 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
34 JOptionPane.showMessageDialog( null, "The sum is " + sum,35 "Results", JOptionPane.PLAIN_MESSAGE );
2003 Prentice Hall, Inc. All rights reserved.
2.5 Another Java Application: Adding Integers
– 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
34 JOptionPane.showMessageDialog( null, "The sum is " + sum,35 "Results", JOptionPane.PLAIN_MESSAGE );
2003 Prentice Hall, Inc. All rights reserved.
2.5 Another Java Application: Adding Integers
Message dialog type Icon Description
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 no icon Displays a dialog that simply contains a
message, with no icon. Fig. 2.12 JOptionPane constants for message dialogs.
Introduction to Computers and Programming
Lecture 4: Mathematical Operators
Professor: Evan KorthNew 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 run-time error?
Basic Mathematical Operators
Each of the operators in the table are binary operators. A binary operator acts on two operands
Java Operation
Arithmetic Operator
Algebraic Expression
Java Expression
Addition + a + b a + b
Subtraction - a – b a – b
Multiplication * ab a * b
Division / a / b a / b
Modulus % a mod b a % b
Integer Division - The Problem
• Suppose you have the following code:
• Using a calculator, the answer is 1.75.• But x can only hold integer values. 1.75 is clearly
not an integer value.
int x;x = 7 / 4;
Integer Division - Solution
• To understand the solution, you need to remember your 3rd Grade Math (really.)
• 7/4 = 1 (Integer Division)• 7%4 = 3 (Modulus Division)
4 743
1
The answer: 1 remainder 3
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: 05 % 10: 5
Modulus Division (cont.)
• Second Example:
• No matter what, your answers must be integers.
5/10 = 0
5%10 = 5
510
0
05
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 isnormally undefined on computer systems andgenerally results in a fatal error.
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.
2003 Prentice Hall, Inc. All rights reserved.
Operator Precedence
• Operator precedence represent rules for evaluating mathematical expressions.
• Every programming language has similar rules.
Operator(s) Operation(s) Order of evaluation (precedence) () Parentheses 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.
*, /, or % Multiplication Division Modulus
Evaluated second. If there are several, they are evaluated left to right.
+ or - Addition Subtraction
Evaluated last. If there are several, they are evaluated left to right.
Operator Precedence
• Hence, option #2 is always correct (multiplication is performed first):
• Example: Find the average of three variables a, b and c
• Do not use: a + b + c / 3 • Use: (a + b + c ) / 3
x = 7 + 3 * 6;Evaluates to x = 7 + 18 = 25
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 = m * x + b ; y = (m * x) + b;– e.g. y = a * b * b + c * b – d; y = (((a * b) * b) + (c * b)) – d;
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
byte 8 bits -128 127short 16 bits -32768 32767int 32 bits -2,147,483,648 2,147,483,647long 64 bits -9,223,372,036,854,770,000 9,223,372,036,854,770,000
float 32 -3.40282347E+38 3.40282347E+38double 64 -1.79769313486231570E+308 1.79769313486231570E+308
Floating point values
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 5Boolean type; if statement
Professor: Evan KorthNew 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• 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.
2003 Prentice Hall, Inc. All rights reserved.
Relational Operators
Not Equal to!=
Equal to==
Less than or equal to
<=
Greater than or equal to
>=
Less than<
Greater than>MeaningOperator
Exampleimport javax.swing.JOptionPane;
public class BoolTest{
public static void main(String[] args){
boolean boolVar;
boolVar = false;System.out.println ("boolVar: " + boolVar);
int a = 10;int b = 10;boolVar = ( a == b);System.out.println ("boolVar: " + boolVar);
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);
}}
boolVar: falseboolVar: falseboolVar: trueboolVar: truetruetruefalsefalsefalsefalsetruetruefalsefalsetruetrue
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
2003 Prentice Hall, Inc. All rights reserved.
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
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
Rectangles represent statements of work. For example:System.out.println();
Diamonds(decision symbol)
contain conditions flow
line
flowline
Connector symbol
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.
if with a twist: if else
• Pseudocode:if some Boolean expression is true do thisotherwise do something else
• Example:if ( grade >= 65 )
System.out.println( "You passed!" );else
System.out.println( "You failed!" );
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 inif (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.
Exampleimport 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);}
}
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 conditionalStatement.
TrueOption
FalseOption
? short-cut operator
colon
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 branches2. You want to execute zero or one of the branches3. You want to execute zero or more branches
• Which would be appropriate for each of the situations above:
– A series of ifs– A series of if / else ifs ending with an else if– A series of if / else ifs ending with an else
1 – c
2 – b
3 – a
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 tableFALSE TRUE
FALSE FALSE FALSETRUE FALSE TRUE
• 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
FALSE TRUEFALSE FALSE TRUETRUE TRUE TRUE
• 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 TRUEFALSE FALSE TRUETRUE 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;
case value2:action(s);break;
…default:
actions(s);break;
}
keyword switch
could use more than one case;if the same actions are required
expression can be a variable ora more complicated expression
actions within a single case do not need bracketsthe default case will be executedin the event that no other case is
The switch Multiple-Selection Structure
• Flowchart of the switch structure
true
false
.
.
.
case a case a action(s)
case b case b action(s) break
false
false
case z case z action(s) break
true
true
default action(s)
2000 Prentice Hall, Inc.All rights reserved.
break
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.
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 KorthNew 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
• 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.
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 intchar c = 'a';int i = c;
– You must explicitly cast an int to a charint 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 += operatorx = 2;x += 1; // same as x = x + 1;System.out.println ("x: " + x);• There are similar operators for *, -, /.%
– x = x * 5 is equivalent to x *= 5;– x = x – 5;is equivalent to x -= 5;– x = x / 5;is equivalent to x /= 5;– x = x % 5;is equivalent to x %= 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){int c = 5;System.out.println (c);System.out.println (c++);System.out.println (c);System.out.println();c = 5;System.out.println (c);System.out.println (++c);System.out.println (c);
}}
Output:
5
5
6
5
6
6
Post Increment
Pre Increment 2000 Prentice Hall, Inc. All rights reserved. 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.
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[]){ int index = 1; while (index <= 10) {
System.out.println ("Index: " + index);index++;
}}
}
Index: 1
Index: 2
Index: 3
...
Index: 8
Index: 9
Index: 10
1. Priming2. Test Condition
3. Update: In this case, you can use either the pre or post increment operator.
While Loop Flowchart
1. PrimingSet index=1
2. Testindex <= 10
3. Print value of index
Update index++
TRUE
FALSE
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); }}
} Here, I have deleted part 3: The update statement (index++).
Index: 1
Index: 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++;
}}
}
Here, I have changedPart 2: the testcondition.
Index: 1
Index: 2
Index: 3
Index: 4
Index: 5
… [forever]
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 product = 2 * producttrue
false
2000 Prentice Hall, Inc. All rights reserved.
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 zeroSet grade counter to one
While grade counter is less than or equal to tenInput the next gradeAdd the grade into the totalAdd one to the grade counter
Set the class average to the total divided by tenPrint the class average
Fig. 4.6 Pseudocode algorithm that uses counter-controlled repetition to solve the class-average problem.
2003 Prentice Hall, Inc. All rights reserved.
1 // Fig. 4.7: Average1.java2 // Class-average program with counter-controlled repetition.3 import javax.swing.JOptionPane;4 5 public class Average1 {6 7 public static void main( String args[] ) 8 {9 int total; // sum of grades input by user10 int gradeCounter; // number of grade to be entered next11 int grade; // grade value12 int average; // average of grades13 14 String gradeString; // grade typed by user15 16 // initialization phase17 total = 0; // initialize total18 gradeCounter = 1; // initialize loop counter19 20 // processing phase21 while ( gradeCounter <= 10 ) { // loop 10 times22 23 // prompt for input and read grade from user24 gradeString = JOptionPane.showInputDialog(25 "Enter integer grade: " );26 27 // convert gradeString to int28 grade = Integer.parseInt( gradeString );29
2003 Prentice Hall, Inc. All rights reserved.
30 total = total + grade; // add grade to total31 gradeCounter = gradeCounter + 1; // increment counter32 33 } // end while34 35 // termination phase36 average = total / 10; // integer division37 38 // display average of exam grades39 JOptionPane.showMessageDialog( null, "Class average is " + 40 average, Class Average", JOptionPane.INFORMATION_MESSAGE );41 42 System.exit( 0 ); // terminate the program43 44 } // end main45 46 } // end class Average1
2003 Prentice Hall, Inc. All rights reserved.
Introduction to Computers and Programming
Lecture 8: More LoopsProfessor: Evan KorthNew 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?
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.
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 variablesInput, sum and count the quiz gradesCalculate 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 zeroInitialize 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 toIf the counter is not equal to zero Set the average to the total divided by the counter Print the averageelse Print “No grades were entered”
2000 Prentice Hall, Inc. All rights reserved.
Initialize total to zeroInitialize 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 totalAdd one to the grade counterInput the next grade (possibly the sentinel)
If the counter is not equal to zeroSet the average to the total divided by the counterPrint the average
elsePrint “No grades were entered”
Fig. 4.8 Class-average problem pseudocode algorithm with sentinel-controlled repetition.
2003 Prentice Hall, Inc. All rights reserved.
2003 Prentice Hall, Inc.All rights reserved.
Outline
Average2.java
1 // Fig. 4.9: Average2.java2 // Class-average program with sentinel-controlled repetition.3 import java.text.DecimalFormat; // class to format numbers4 import javax.swing.JOptionPane;5 6 public class Average2 {7 8 public static void main( String args[] )9 {10 int total; // sum of grades11 int gradeCounter; // number of grades entered12 int grade; // grade value13 14 double average; // number with decimal point for average15 16 String gradeString; // grade typed by user17 18 // initialization phase19 total = 0; // initialize total20 gradeCounter = 0; // initialize loop counter21 22 // processing phase23 // get first grade from user 24 gradeString = JOptionPane.showInputDialog(25 "Enter Integer Grade or -1 to Quit:" );26 27 // convert gradeString to int 28 grade = Integer.parseInt( gradeString ); 29
2003 Prentice Hall, Inc.All rights reserved.
Outline
Average2.java
Line 31
Line 45
30 // loop until sentinel value read from user31 while ( grade != -1 ) { 32 total = total + grade; // add grade to total33 gradeCounter = gradeCounter + 1; // increment counter34 35 // get next grade from user 36 gradeString = JOptionPane.showInputDialog(37 "Enter Integer Grade or -1 to Quit:" );38 39 // convert gradeString to int 40 grade = Integer.parseInt( gradeString ); 41 42 } // end while43 44 // termination phase45 46 47 // if user entered at least one grade...48 if ( gradeCounter != 0 ) {49 50 // calculate average of all grades entered51 average = (double) total / gradeCounter; 52 53 // display average with two digits of precision54 JOptionPane.showMessageDialog( null,55 "Class average is " + average ,56 "Class Average", JOptionPane.INFORMATION_MESSAGE );57 58 } // end if part of if...else59
loop until gradeCounter equals sentinel value (-1)
2003 Prentice Hall, Inc.All rights reserved.
Outline
Average2.java
60 else // if no grades entered, output appropriate message61 JOptionPane.showMessageDialog( null, "No grades were entered",62 "Class Average", JOptionPane.INFORMATION_MESSAGE );63 64 System.exit( 0 ); // terminate application65 66 } // end main67 68 } // end class Average2
2003 Prentice Hall, Inc. All rights reserved.
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.
2003 Prentice Hall, Inc. All rights reserved.
Nested control structures
• Top level outlineAnalyze exam results and decide if tuition should be raised
• First RefinementInitialize variablesInput the ten quiz grades and count passes and failuresPrint a summary of the exam results and decide if tuition should
be raised
• Refine Initialize variables to Initialize passes to zeroInitialize failures to zeroInitialize student counter to one
2003 Prentice Hall, Inc. All rights reserved.
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 tenInput the next exam resultIf the student passed Add one to passeselse Add one to failuresAdd one to student counter
• Refine Print a summary of the exam results and decide if tuition should be raised to
Print the number of passesPrint the number of failuresIf more than eight students passed
Print “Raise tuition”
2003 Prentice Hall, Inc. All rights reserved.
2003 Prentice Hall, Inc. All rights reserved.
Initialize passes to zeroInitialize failures to zeroInitialize 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 passesPrint 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.
2003 Prentice Hall, Inc.All rights reserved.
Outline
Analysis.java
Line 19
Line 29
1 // Fig. 4.11: Analysis.java2 // Analysis of examination results.3 import javax.swing.JOptionPane;4 5 public class Analysis {6 7 public static void main( String args[] ) 8 {9 // initializing variables in declarations10 int passes = 0; // number of passes 11 int failures = 0; // number of failures12 int studentCounter = 1; // student counter 13 int result; // one exam result14 15 String input; // user-entered value16 String output; // output string17 18 // process 10 students using counter-controlled loop19 while ( studentCounter <= 10 ) {20 21 // prompt user for input and obtain value from user22 input = JOptionPane.showInputDialog(23 "Enter result (1 = pass, 2 = fail)" );24 25 // convert result to int26 result = Integer.parseInt( input );27 28 // if result 1, increment passes; if...else nested in while29 if ( result == 1 ) 30 passes = passes + 1;
Loop until student counter is greater than 10
Nested control structure
2003 Prentice Hall, Inc.All rights reserved.
Outline
Analysis.java
31 32 else // if result not 1, increment failures 33 failures = failures + 1; 34 35 // increment studentCounter so loop eventually terminates36 studentCounter = studentCounter + 1; 37 38 } // end while39 40 // termination phase; prepare and display results41 output = "Passed: " + passes + "\nFailed: " + failures;42 43 // determine whether more than 8 students passed44 if ( passes > 8 )45 output = output + "\nRaise Tuition";46 47 JOptionPane.showMessageDialog( null, output,48 "Analysis of Examination Results",49 JOptionPane.INFORMATION_MESSAGE );50 51 System.exit( 0 ); // terminate application52 53 } // end main54 55 } // end class Analysis
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
true
false
action(s)
condition
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
• 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 KorthNew 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?
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;
for (counter =1;counter <= 10;counter++)
System.out.println (counter);
1. Priming: Set 1. Priming: Set the start value.the start value.
2. Test 2. Test Condition: Set Condition: Set the stop value.the stop value.
3. Update: Update the 3. Update: Update the value.value.
Note that each section Note that each section is separated by a is separated by a semicolon.semicolon.
for Loop Flowchart
1: Priming1: PrimingSet counter=1Set counter=1
2: Test2: Testcounter counter <= 10<= 10
Body: print counterBody: print counterTRUETRUE
FALSEFALSE
3: Update 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 tofor ( 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--)orfor (i = 1; j + i <= 10; i++, j++){code;
}
• 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 KorthNew 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?
Nested For Loops• It is also possible to place a for
loop inside another for loop.
int rows, columns; for (rows = 1; rows <= 5; rows++) {
for (columns=1; columns<=10; columns++) System.out.print ("*");
System.out.println ();}
Outer LoopOuter Loop
Inner LoopInner Loop
Output:Output:****************************************************************************************************
Nested For Loops, Example #2
int rows, columns;
for (rows=1; rows<=5; rows++) {for (columns=1; columns<=rows; columns++)
System.out.print ("*");System.out.println ();
}
Output:Output:******************************
Outer LoopOuter Loop
Inner LoopInner Loop
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
J ava Keywords abstract assert boolean break byte case catch char class continue default do double else extends final finally float for if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while Keywords that are reserved, but not currently used const goto Fig. 4.2 J ava keywords.
2003 Prentice Hall, Inc. All rights reserved.
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.
0.01.02.03.04.0NumFDCBALetter