Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction To Computers and Programming Lecture 2: Your first program Professor: Evan Korth New York University.

Similar presentations


Presentation on theme: "Introduction To Computers and Programming Lecture 2: Your first program Professor: Evan Korth New York University."— Presentation transcript:

1 Introduction To Computers and Programming Lecture 2: Your first program Professor: Evan Korth New York University

2 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

3 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?

4 Syntax vs. Style Syntax: The rules of a language Style: Good programming practices

5 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.

6 A Sample Java Program Java uses some notations that may appear strange at first. Let’s look at a sample program.

7 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

8 Welcome1.java Program Output
// Fig. 2.1: Welcome1.java // Text-printing program. 3 public class Welcome1 { 5 // main method begins execution of Java application public static void main( String args[] ) { System.out.println( "Welcome to Java Programming!" ); 10 } // end method main 12 13 } // end class Welcome1 Welcome1.java Program Output Welcome to Java Programming!

9 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 */ // Fig. 2.1: Welcome1.java (modified by Evan Korth)

10 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 // 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)

11 2.2 A Simple Program: Printing a Line of Text
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 public class Welcome1 { (modified by Evan Korth)

12 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 public class Welcome1 { (modified by Evan Korth)

13 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 public class Welcome1 { public static void main( String args[] ) (modified by Evan Korth)

14 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. public static void main( String args[] ) { (modified by Evan Korth)

15 2.2 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 ; (modified by Evan Korth)

16 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 } // end method main 13 } // end class Welcome1

17 Any code enclosed between braces is called a block.
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).

18 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

19 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.

20 2.3 Modifying Our First Java Program
Modify example in Fig. 2.1 to print same contents using different code

21 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 System.out.print( "Welcome to " ); System.out.println( "Java Programming!" );

22 // Fig. 2.3: Welcome2.java // Printing a line of text with multiple statements. 3 public class Welcome2 { 5 // main method begins execution of Java application public static void main( String args[] ) { System.out.print( "Welcome to " ); System.out.println( "Java Programming!" ); 11 } // end method main 13 14 } // end class Welcome2 Welcome2.java 1. Comments 2. Blank line 3. Begin class Welcome Method main 4. Method System.out.print 4.1 Method System.out.println 5. end main, Welcome2 Program Output System.out.print keeps the cursor on the same line, so System.out.println continues on the same line. Welcome to Java Programming!

23 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!" ); System.out.println( "Welcome\nto\nJava\nProgramming!" );

24 Notice how a new line is output for each \n escape sequence.
// Fig. 2.4: Welcome3.java // Printing multiple lines of text with a single statement. 3 public class Welcome3 { 5 // main method begins execution of Java application public static void main( String args[] ) { System.out.println( "Welcome\nto\nJava\nProgramming!" ); 10 } // end method main 12 13 } // end class Welcome3 Welcome3.java 1. main 2. System.out.println (uses \n for new line) Program Output Notice how a new line is output for each \n escape sequence. Welcome to Java Programming!

25 2.3 Modifying Our First Java Program
Escape characters Backslash ( \ ) Indicates special characters be output

26 2.4 Displaying Text in a Dialog Box
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)

27 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

28 // Fig. 2.6: Welcome4.java // Printing multiple lines in a dialog box. 3 // Java packages import javax.swing.JOptionPane; // program uses JOptionPane 6 public class Welcome4 { 8 // main method begins execution of Java application public static void main( String args[] ) { JOptionPane.showMessageDialog( null, "Welcome\nto\nJava\nProgramming!" ); 14 System.exit( 0 ); // terminate application with window 16 } // end method main 18 19 } // end class Welcome4 1 // Fig. 2.6: Welcome4.java 2 // Printing multiple lines in a dialog box 3 import javax.swing.JOptionPane; // import class JOptionPane Welcome4.java 1. import declaration 2. Class Welcome main 2.2 showMessageDialog 2.3 System.exit Program Output 4 5 public class Welcome4 { 6 public static void main( String args] ) 7 { JOptionPane.showMessageDialog( null, "Welcome\nto\nJava\nProgramming!" ); 10 System.exit( 0 ); // terminate the program 12 }

29 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 // Java packages import javax.swing.JOptionPane; // program uses OptionPane

30 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 JOptionPane.showMessageDialog( null, "Welcome\nto\nJava\nProgramming!" ); (modified by Evan Korth)

31 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

32 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 System.exit( 0 ); // terminate application with window

33 Introduction to Computers and Programming Lecture 3: Variables and Input Professor: Evan Korth New York University

34 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

35 What’s wrong with this line of code?
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?

36 What’s wrong with this program?
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

37 Variables

38 Variable: a small piece or “chunk” of data.
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.

39 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.

40 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, (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.

41 It is useful to think of a variable as a bucket of data.
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 is a variable containing the value 200, and can contain only integers. 200 balance

42 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)

43 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

44 (modified by Evan Korth)
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)

45 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.

46 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

47 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 Variable Name semicolon Data Type Assignment Statements x: 5 y: 10 z: 15

48 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.

49 Read the assignment operator as “GETS” not “EQUALS!”
= 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

50 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.

51 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.

52 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.

53 Revisit Errors

54 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.

55 Runtime errors fall into two categories.
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.

56 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

57 Declare variables: name and type.
1 // Fig. 2.9: Addition.java 2 // Addition program that displays the sum of two numbers. 3 4 // Java packages 5 import javax.swing.JOptionPane; // program uses JOptionPane 6 7 public class Addition { 8 // main method begins execution of Java application public static void main( String args[] ) { String firstNumber; // first string entered by user String secondNumber; // second string entered by user 14 int number1; // first number to add int number2; // second number to add int sum; // sum of number1 and number2 18 // read in first number from user as a String firstNumber = JOptionPane.showInputDialog( "Enter first integer" ); 21 // read in second number from user as a String secondNumber = JOptionPane.showInputDialog( "Enter second integer" ); 25 // convert numbers from type String to type int number1 = Integer.parseInt( firstNumber ); number2 = Integer.parseInt( secondNumber ); 29 // add numbers sum = number1 + number2; 32 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 Declare variables: name and type. Input first integer as a String, assign to firstNumber. Convert strings to integers. Add, place result in sum.

58 Program output 33 // display result
JOptionPane.showMessageDialog( null, "The sum is " + sum, "Results", JOptionPane.PLAIN_MESSAGE ); 36 System.exit( 0 ); // terminate application with window 38 } // end method main 40 41 } // end class Addition Program output

59 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 import javax.swing.JOptionPane; // program uses JOptionPane public class Addition { String firstNumber; // first string entered by user String secondNumber; // second string entered by user

60 2.5 Another Java Application: Adding Integers
String firstNumber; // first string entered by user String secondNumber; // 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 ; 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;

61 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 int number1; // first number to add int number2; // second number to add int sum; // sum of number1 and number2

62 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 firstNumber = JOptionPane.showInputDialog( "Enter first integer" ); (modified by Evan Korth)

63 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" ) firstNumber = JOptionPane.showInputDialog( "Enter first integer" );

64 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 secondNumber = JOptionPane.showInputDialog( "Enter second integer" ); number1 = Integer.parseInt( firstNumber ); number2 = Integer.parseInt( secondNumber ); (modified by Evan Korth)

65 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 sum = number1 + number2;

66 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 JOptionPane.showMessageDialog( null, "The sum is " + sum, "Results", JOptionPane.PLAIN_MESSAGE );

67 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 JOptionPane.showMessageDialog( null, "The sum is " + sum, "Results", JOptionPane.PLAIN_MESSAGE );

68 2.5 Another Java Application: Adding Integers

69 Introduction to Computers and Programming Lecture 4: Mathematical Operators Professor: Evan Korth New York University

70 Basic Mathematical Operators Integer Division Operator Precedence
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

71 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.

72 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?

73 Basic Mathematical Operators

74 Basic Mathematical Operators
Java Operation Arithmetic Operator Algebraic Expression Java Expression Addition + a + b Subtraction - a – b Multiplication * ab a * b Division / 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

75 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 is clearly not an integer value. int x; x = 7 / 4;

76 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) 1 4 7 4 3 The answer: 1 remainder 3

77 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

78 Modulus Division (cont.)
Second Example: No matter what, your answers must be integers. 5/10 = 0 5%10 = 5 10 5 5

79 Just divide by 2. If the remainder (modulus) is 0, the number is even.
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.

80 Operator Precedence

81 Perform addition first: 7 + 3 = 10  10 * 6 = 60
Operator Precedence Here’s another problem. What’s the answer to this? x = * 6; Two Options (depending on the order of operations): Perform addition first: = 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.

82 Operator Precedence Operator precedence represent rules for evaluating mathematical expressions. Every programming language has similar rules.

83 x = 7 + 3 * 6; Evaluates to x = 7 + 18 = 25 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 = * 6; Evaluates to x = = 25

84 Are your really good friends
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;

85 Floating Point Data Types

86 Data type that can hold numbers with fractional values
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.

87 double Example Sum: 276.5 // 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

88 Numeric type ranges in Java
Integers Floating point values

89 Example: Find an Average
Suppose you want to determine a student’s average. int totalTests = 4; double average = / totalTests;

90 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 = ( )/ totalTests;

91 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 There are actually three ways to solve this problem.

92 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 = ( )/ totalTests;

93 Rules of Promotion 2. Use a double literal for one of the values on the right hand side double average = ( ) / 4; 3. Use a Cast Operator int totalTests = 4; double average = ( )/(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.

94 final int TOTAL_GRADES = 4; Used to avoid “magic numbers” in code.
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).

95 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.

96 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.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)

97 Road map char data type Reading Liang 5: Chapter 2: 2.7.4; 2.9;

98 Introduction to Computers and Programming Lecture 5 Boolean type; if statement Professor: Evan Korth New York University

99 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 – Liang 6 & 7: Chapter 3: 3.1 – 3.3

100 review div mod worksheet

101 Why do we use constants in our programs instead of literal values?
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?

102 What happens if you go beyond a type’s upper bound?
Review What happens if you go beyond a type’s upper bound? For example: int i = ; 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 = ; What if you go beyond an integer type’s bounds using arithmetic? Which has higher precedence: + (addition) % (modulus)

103 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.

104 Relational Operators Meaning Operator Not Equal to != Equal to ==
Less than or equal to <= Greater than or equal to >= Less than < Greater than > Meaning Operator

105 Example import 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 (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: false boolVar: true true false

106 Remember Gets not Equals! Will not evaluate to true or false
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 ==)

107 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

108 Algorithm: procedure in terms of
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

109  2000 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.

110 Different shapes have different meaning.
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.

111 Flow Chart Basics 1 Connector symbol flow line Diamonds
(decision symbol) contain conditions Rectangles represent statements of work. For example: System.out.println(); flow line

112 Control Structures

113 Control the flow of a program
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

114 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.

115 The if structure Pseudocode: Example:
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.

116 Another if example if ( temperature >= 85 ) {
System.out.println( "It is hot out!" ); }

117 if Flow Chart temperature >=85 true print “It is hot” false

118 Pseudocode: Example: if ( grade >= 65 ) if with a twist: if else
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!" );

119 if/else Flow Chart False True grade >=60 Print “You failed”
False True grade >=60 Print “You failed” Print “You passed”

120 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!" ); }

121 Avoid writing code like this:
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

122 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); 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.

123 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);

124 Introduction to Computers and Programming Lecture 6 Professor: Evan Korth New York University

125 Road Map if / else continued Logical operators switch statement
Nested if / else statements Logical operators &&, ||, ^ ! &, | switch statement Reading: Liang 5: chapter 2: 2.10;chapter 3: 3.2 Liang 6: chapter 3: Liang 7: chapter 3:

126 What is the output of the following code fragment?
review What is the output of the following code fragment? int a = 100; if (a = 100) System.out.println (" a is equal to " + a); int a = 100, b = 1; if (a < b) System.out.println ("a is less than b");

127 What is the output of the following code fragment?
review What is the output of the following code fragment? int a = 100; if (a != 100); System.out.println (" a is equal to " + a); int a = 100, b = 1; if (a < b) System.out.println ("a is less than b"); System.out.println ("Thank you");

128 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 Statement. ? short- cut operator True Option colon False Option

129 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"); } System.out.println("You failed");

130 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");

131 Choosing the flavor of your if
When you have multiple possible branches, you can have any of the following situations: You want to execute exactly one of the branches You want to execute zero or one of the branches 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

132 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");

133 && - 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 For example: ((total > 50) && (status == 0))

134 || - 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 For example: ((total > 50) || (status == 0))

135 ^ - 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 For example: ((person1 == 1) ^ (person2 == 1))

136 Reverses the truth or falsity of expression a Boolean expression
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

137 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.

138 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.

139 switch Multiple-Selection Structure
switch (expression) { case value1: action(s); break; case value2: default: actions(s); } keyword switch expression can be a variable or a more complicated expression 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

140 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 case z case z action(s) default action(s) break  2000 Prentice Hall, Inc. All rights reserved.

141 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.

142 Style Considerations

143 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.

144 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?)

145 Pick good spots to break up a long line
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

146 Put a comment after the right brace!
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.

147 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… }

148 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.

149 Introduction to Computers and Programming Lecture 7: assignment operators and introduction to while loops Instructor: Evan Korth New York University

150 Introduction to while loops Reading
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)

151 True or False: An int variable can contain any integer.
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)

152 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"); if ((a == 60) || (b <= 100))

153 What is the output of this switch statement?
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); }

154 char data type

155 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 Note: chars use single quotes. We have seen that Strings use double quotes.

156 ASCII Table Source: Liang

157 letter = (char) (letter + 1);
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.

158 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.

159 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).

160 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?

161 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 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.

162 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.

163 One option is to use the += operator x = 2;
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 * 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.

164 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.

165 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.

166 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 = 5; System.out.println (++c); } Post Increment Output: 5 6 Pre Increment  2000 Prentice Hall, Inc. All rights reserved. Modified by Evan Korth

167 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.

168 Introduction to While Loops

169 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.

170 while loop (continued)
For example (in pseudocode) while (some Boolean expression is true) { do this (again and again...) }

171 Parts of a While Loop Every while loop will always contain three main elements: Priming: initialize your variables. Testing: test against some known condition. Updating: updates part (or all) of the expression that is tested.

172 Simple While Loop public class While1 {
public static void main (String args[]) int index = 1; while (index <= 10) System.out.println ("Index: " + index); index++; } 1. Priming 2. Test Condition Index: 1 Index: 2 Index: 3 ... Index: 8 Index: 9 Index: 10 3. Update: In this case, you can use either the pre or post increment operator.

173 While Loop Flowchart 1. Priming Set index=1 TRUE
2. Test index <= 10 TRUE 3. Print value of index Update index++ FALSE

174 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.

175 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: 1 … [forever] Here, I have deleted part 3: The update statement (index++).

176 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: 1 Index: 2 Index: 3 Index: 4 Index: 5 … [forever] Here, I have changed Part 2: the test condition.

177 While Loops: Examples

178  2000 Prentice Hall, Inc. All rights reserved.
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

179  2000 Prentice Hall, Inc. All rights reserved.
While Loop Example Example: int product = 2; while ( product <= 1000 ) product = 2 * product; product <= 1000 product = 2 * product true false  2000 Prentice Hall, Inc. All rights reserved.

180  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.

181 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.

182  2003 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.

183  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 Pseudocode algorithm that uses counter-controlled repetition to solve the class-average problem.  2003 Prentice Hall, Inc. All rights reserved.

184  2003 Prentice Hall, Inc. All rights reserved.
1 // Fig. 4.7: Average1.java 2 // Class-average program with counter-controlled repetition. 3 import javax.swing.JOptionPane; 4 5 public class Average1 { 6 public static void main( String args[] ) { int total; // sum of grades input by user int gradeCounter; // number of grade to be entered next int grade; // grade value int average; // average of grades 13 String gradeString; // grade typed by user 15 // initialization phase total = 0; // initialize total gradeCounter = 1; // initialize loop counter 19 // processing phase while ( gradeCounter <= 10 ) { // loop 10 times 22 // prompt for input and read grade from user gradeString = JOptionPane.showInputDialog( "Enter integer grade: " ); 26 // convert gradeString to int grade = Integer.parseInt( gradeString ); 29  2003 Prentice Hall, Inc. All rights reserved.

185  2003 Prentice Hall, Inc. All rights reserved.
total = total + grade; // add grade to total gradeCounter = gradeCounter + 1; // increment counter 32 } // end while 34 // termination phase average = total / 10; // integer division 37 // display average of exam grades JOptionPane.showMessageDialog( null, "Class average is " + average, Class Average", JOptionPane.INFORMATION_MESSAGE ); 41 System.exit( 0 ); // terminate the program 43 } // end main 45 46 } // end class Average1  2003 Prentice Hall, Inc. All rights reserved.

186 Introduction to Computers and Programming Lecture 8: More Loops Professor: Evan Korth New York University

187 Reading 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

188 What are three ways to rewrite:
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?

189 What is the value of variable c?
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?

190 Sentinels

191 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

192 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

193 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

194 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" );

195 /* 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 */ } System.exit (0);

196 Style: Remind user each iteration what the sentinel is
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.

197 Case Study: Using Sentinel Controlled Loops

198 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.

199 Formulating Algorithms with 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.

200 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.

201 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.

202  2003 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 Class-average problem pseudocode algorithm with sentinel-controlled repetition.  2003 Prentice Hall, Inc. All rights reserved.

203 Average2.java 1 // Fig. 4.9: Average2.java
// Class-average program with sentinel-controlled repetition. import java.text.DecimalFormat; // class to format numbers import javax.swing.JOptionPane; 5 public class Average2 { 7 public static void main( String args[] ) { int total; // sum of grades int gradeCounter; // number of grades entered int grade; // grade value 13 double average; // number with decimal point for average 15 String gradeString; // grade typed by user 17 // initialization phase total = 0; // initialize total gradeCounter = 0; // initialize loop counter 21 // processing phase // get first grade from user gradeString = JOptionPane.showInputDialog( "Enter Integer Grade or -1 to Quit:" ); 26 // convert gradeString to int grade = Integer.parseInt( gradeString ); 29 Average2.java

204 loop until gradeCounter equals sentinel value (-1)
// loop until sentinel value read from user while ( grade != -1 ) { total = total + grade; // add grade to total gradeCounter = gradeCounter + 1; // increment counter 34 // get next grade from user gradeString = JOptionPane.showInputDialog( "Enter Integer Grade or -1 to Quit:" ); 38 // convert gradeString to int grade = Integer.parseInt( gradeString ); 41 } // end while 43 // termination phase 45 46 // if user entered at least one grade... if ( gradeCounter != 0 ) { 49 // calculate average of all grades entered average = (double) total / gradeCounter; 52 // display average with two digits of precision JOptionPane.showMessageDialog( null, "Class average is " + average , "Class Average", JOptionPane.INFORMATION_MESSAGE ); 57 } // end if part of if...else 59 loop until gradeCounter equals sentinel value (-1) Average2.java Line 31 Line 45

205 60 else // if no grades entered, output appropriate message
JOptionPane.showMessageDialog( null, "No grades were entered", "Class Average", JOptionPane.INFORMATION_MESSAGE ); 63 System.exit( 0 ); // terminate application 65 } // end main 67 68 } // end class Average2 Average2.java

206 Case Study: Nested Control Structures

207 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.

208 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.

209 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.

210  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 Pseudocode for examination-results problem.  2003 Prentice Hall, Inc. All rights reserved.

211 Analysis.java Line 19 Line 29
// Fig. 4.11: Analysis.java // Analysis of examination results. import javax.swing.JOptionPane; 4 public class Analysis { 6 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 14 String input; // user-entered value String output; // output string 17 // process 10 students using counter-controlled loop while ( studentCounter <= 10 ) { 20 // prompt user for input and obtain value from user input = JOptionPane.showInputDialog( "Enter result (1 = pass, 2 = fail)" ); 24 // convert result to int result = Integer.parseInt( input ); 27 // if result 1, increment passes; if...else nested in while if ( result == 1 ) passes = passes + 1; Loop until student counter is greater than 10 Analysis.java Line 19 Line 29 Nested control structure

212 Analysis.java 31 32 else // if result not 1, increment failures
failures = failures + 1; 34 // increment studentCounter so loop eventually terminates studentCounter = studentCounter + 1; 37 } // end while 39 // termination phase; prepare and display results output = "Passed: " + passes + "\nFailed: " + failures; 42 // determine whether more than 8 students passed if ( passes > 8 ) output = output + "\nRaise Tuition"; 46 JOptionPane.showMessageDialog( null, output, "Analysis of Examination Results", JOptionPane.INFORMATION_MESSAGE ); 50 System.exit( 0 ); // terminate application 52 } // end main 54 55 } // end class Analysis Analysis.java

213 do/while Loop

214 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 );

215 4.8 The do/while Repetition Structure
Flowchart of the do/while repetition structure true false action(s) condition

216 public class DoWhileTest
{ public static void main(String args[]) int counter; counter = 1; do System.out.println ("counter: "+ counter); counter ++; } while (counter <= 10); }

217 Using a semi-colon after the while statement One off errors
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

218 Summary of Looping so far

219 Two broad types of loops:
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.

220 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.

221 Introduction to Computers and Programming Lecture 9: For Loops Professor: Evan Korth New York University

222 Introduction to for loops Good practice and style using for loops
Road map Introduction to for loops Good practice and style using for loops Reading: Liang 5: Chapter 3: (up to nested for loops) Liang 6: Chapter 4: 4.4, 4.5 Liang 7: Chapter 4 : 4.4, 4.5

223 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?

224 For Loops

225 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.

226 Loop types (reminder) Indefinite Loop: Definite 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

227 Another type of loop in Java is the for loop.
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.

228 for loops are good for creating definite loops.
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 the start value. 2. Test Condition: Set the stop value. 3. Update: Update the value. Note that each section is separated by a semicolon.

229 for Loop Flowchart 1: Priming Set counter=1 2: Test TRUE counter
<= 10 TRUE Body: print counter 3: Update counter++; FALSE

230 Infinite Loop You can still end up with an infinite loop when using for loops for (counter = 0; counter <= 10; counter--)

231 The limit can be a variable: for ( i = 1; i <= limit; i++)
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

232 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.

233 Commas known here as comma operators
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; j + i <= 10; i++, j++) { code; }  2000 Prentice Hall, Inc. All rights reserved. Modified by Evan Korth

234 Do not use a float or double for the counter
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!

235 In the first example, shown here, the following counter < 10
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 */

236 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

237 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

238 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).

239 Introduction to Computers and Programming Lecture 10: For Loops Professor: Evan Korth New York University

240 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?

241 Road map break continue Reading: Liang 6: Chapter 4: 4.9

242 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 (); } Output: ********** Outer Loop Inner Loop

243 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: * ** *** **** ***** Outer Loop Inner Loop

244 break and continue

245 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.

246 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... */ }

247 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.

248 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... */   } }

249  2003 Prentice Hall, Inc. All rights reserved.
Java Keywords  2003 Prentice Hall, Inc. All rights reserved.

250 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.0 1.0 2.0 3.0 4.0 Num F D C B A Letter

251 Structured Programming: Summary

252 Repetition Structures
Summary Sequence Statement follow one another Selection Structures if if/else if/else if/else switch Repetition Structures while do/while for


Download ppt "Introduction To Computers and Programming Lecture 2: Your first program Professor: Evan Korth New York University."

Similar presentations


Ads by Google