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

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

  • View
    223

  • Download
    0

Embed Size (px)

Citation preview

  • Slide 1
  • Slide 2
  • Introduction To Computers and Programming Lecture 2: Your first program Professor: Evan Korth New York University
  • Slide 3
  • 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
  • Slide 4
  • 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?
  • Slide 5
  • Syntax vs. Style Syntax: The rules of a language Style: Good programming practices
  • Slide 6
  • 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.
  • Slide 7
  • A Sample Java Program Java uses some notations that may appear strange at first. Lets look at a sample program.
  • Slide 8
  • 2003 Prentice Hall, Inc. All rights reserved. 2.2A 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
  • Slide 9
  • 2003 Prentice Hall, Inc. All rights reserved. Outline Welcome1.java Program Output 1 // Fig. 2.1: Welcome1.java 2 // Text-printing program. 3 4 public class Welcome1 { 5 6 // main method begins execution of Java application 7 public static void main( String args[] ) 8 { 9 System.out.println( "Welcome to Java Programming!" ); 10 11 } // end method main 12 13 } // end class Welcome1 Welcome to Java Programming!
  • Slide 10
  • 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)
  • Slide 11
  • 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)
  • Slide 12
  • 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.2A Simple Program: Printing a Line of Text 4 public class Welcome1 { (modified by Evan Korth )
  • Slide 13
  • 2003 Prentice Hall, Inc. All rights reserved. 2.2A 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 )
  • Slide 14
  • 2003 Prentice Hall, Inc. All rights reserved. 2.2A 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 )
  • Slide 15
  • 2003 Prentice Hall, Inc. All rights reserved. 2.2A 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 )
  • Slide 16
  • 2003 Prentice Hall, Inc. All rights reserved. 2.2A 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 )
  • Slide 17
  • 2003 Prentice Hall, Inc. All rights reserved. 2.2A 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
  • Slide 18
  • 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).
  • Slide 19
  • 2003 Prentice Hall, Inc. All rights reserved. 2.2A 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 Lets see how to compile it with our IDE. Compile Execute
  • Slide 20
  • 2003 Prentice Hall, Inc. All rights reserved. 2.2A 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.2Executing Welcome1 in a Microsoft Windows 2000 Command Prompt.
  • Slide 21
  • 2003 Prentice Hall, Inc. All rights reserved. 2.3Modifying Our First Java Program Modify example in Fig. 2.1 to print same contents using different code
  • Slide 22
  • 2003 Prentice Hall, Inc. All rights reserved. 2.3Modifying 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!" );
  • Slide 23
  • 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.prin t 4.1 Method System.out.prin tln 5. end main, Welcome2 Program Output Welcome to Java Programming! 1 // Fig. 2.3: Welcome2.java 2 // Printing a line of text with multiple statements. 3 4 public class Welcome2 { 5 6 // main method begins execution of Java application 7 public static void main( String args[] ) 8 { 9 System.out.print( "Welcome to " ); 10 System.out.println( "Java Programming!" ); 11 12 } // end method main 13 14 } // end class Welcome2 System.out.print keeps the cursor on the same line, so System.out.println continues on the same line.
  • Slide 24
  • 2003 Prentice Hall, Inc. All rights reserved. 2.3Modifying 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!" );
  • Slide 25
  • 2003 Prentice Hall, Inc. All rights reserved. Outline Welcome3.java 1. main 2. System.out.prin tln (uses \n for new line) Program Output 1 // Fig. 2.4: Welcome3.java 2 // Printing multiple lines of text with a single statement. 3 4 public class Welcome3 { 5 6 // main method begins execution of Java application 7 public static void main( String args[] ) 8 { 9 System.out.println( "Welcome\nto\nJava\nProgramming!" ); 10 11 } // end method main 12 13 } // end class Welcome3 Welcome to Java Programming! Notice how a new line is output for each \n escape sequence.
  • Slide 26
  • 2003 Prentice Hall, Inc. All rights reserved. 2.3Modifying Our First Java Program Escape characters Backslash ( \ ) Indicates special characters be output
  • Slide 27
  • 2003 Prentice Hall, Inc. All rights reserved. 2.4Displaying 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)
  • Slide 28
  • 2003 Prentice Hall, Inc. All rights reserved. 2.4Displaying 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
  • Slide 29
  • 2003 Prentice Hall, Inc. All rights reserved. Outline Welcome4.java 1. import declaration 2. Class Welcome4 2.1 main 2.2 showMessageDial og 2.3 System.exit Program Output 1// Fig. 2.6: Welcome4.java 2// Printing multiple lines in a dialog box 3import javax.swing.JOptionPane; // import class JOptionPane 4 5public 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.java 2 // Printing multiple lines in a dialog box. 3 4 // Java packages 5 import javax.swing.JOptionPane; // program uses JOptionPane 6 7 public class Welcome4 { 8 9 // main method begins execution of Java application 10 public static void main( String args[] ) 11 { 12 JOptionPane.showMessageDialog( 13 null, "Welcome\nto\nJava\nProgramming!" ); 14 15 System.exit( 0 ); // terminate application with window 16 17 } // end method main 18 19 } // end class Welcome4
  • Slide 30
  • 2003 Prentice Hall, Inc. All rights reserved. 2.4Displaying 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
  • Slide 31
  • 2003 Prentice Hall, Inc. All rights reserved. 2.4Displaying 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 )
  • Slide 32
  • 2003 Prentice Hall, Inc. All rights reserved. 2.4Displaying 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
  • Slide 33
  • 2003 Prentice Hall, Inc. All rights reserved. 2.4Displaying 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
  • Slide 34
  • Introduction to Computers and Programming Lecture 3: Variables and Input Professor: Evan Korth New York University
  • Slide 35
  • 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
  • Slide 36
  • Review Whats wrong with this line of code? System.out.println ("He said, "Hello""); Whats 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?
  • Slide 37
  • Review Whats 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
  • Slide 38
  • Variables
  • Slide 39
  • 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.
  • Slide 40
  • 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.
  • Slide 41
  • Javas (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.
  • Slide 42
  • 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 variable containing the value 200, and can contain only integers.
  • Slide 43
  • Memory Concepts Variable names correspond to locations in the computers 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 variables value can just be used and not destroyed (called non-destructive read-out)
  • Slide 44
  • 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
  • Slide 45
  • 2003 Prentice Hall, Inc. All rights reserved. 2.2Rules 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 )
  • Slide 46
  • 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.
  • Slide 47
  • 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
  • Slide 48
  • 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: 5 y: 10 z: 15 semicolon
  • Slide 49
  • 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.
  • Slide 50
  • Assignment Operator = Read the assignment operator as GETS not EQUALS! This is an assignment of whats 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
  • Slide 51
  • 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.
  • Slide 52
  • 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.
  • Slide 53
  • 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.
  • Slide 54
  • Revisit Errors
  • Slide 55
  • 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.
  • Slide 56
  • 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.
  • Slide 57
  • 2003 Prentice Hall, Inc. All rights reserved. 2.5Another 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
  • Slide 58
  • 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.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 9 // main method begins execution of Java application 10 public static void main( String args[] ) 11 { 12 String firstNumber; // first string entered by user 13 String secondNumber; // second string entered by user 14 15 int number1; // first number to add 16 int number2; // second number to add 17 int sum; // sum of number1 and number2 18 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 int 27 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.
  • Slide 59
  • 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 window 38 39 } // end method main 40 41 } // end class Addition
  • Slide 60
  • 2003 Prentice Hall, Inc. All rights reserved. 2.5Another 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
  • Slide 61
  • 2003 Prentice Hall, Inc. All rights reserved. 2.5Another 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
  • Slide 62
  • 2003 Prentice Hall, Inc. All rights reserved. 2.5Another 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
  • Slide 63
  • 2003 Prentice Hall, Inc. All rights reserved. 2.5Another 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)
  • Slide 64
  • 2003 Prentice Hall, Inc. All rights reserved. 2.5Another 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" );
  • Slide 65
  • 2003 Prentice Hall, Inc. All rights reserved. 2.5Another 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)
  • Slide 66
  • 2003 Prentice Hall, Inc. All rights reserved. 2.5Another 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;
  • Slide 67
  • 2003 Prentice Hall, Inc. All rights reserved. 2.5Another 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 );
  • Slide 68
  • 2003 Prentice Hall, Inc. All rights reserved. 2.5Another 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 );
  • Slide 69
  • 2003 Prentice Hall, Inc. All rights reserved. 2.5Another Java Application: Adding Integers
  • Slide 70
  • Introduction to Computers and Programming Lecture 4: Mathematical Operators Professor: Evan Korth New York University
  • Slide 71
  • 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
  • Slide 72
  • 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.
  • Slide 73
  • 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?
  • Slide 74
  • Basic Mathematical Operators
  • Slide 75
  • 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 Subtraction -a b Multiplication *aba * b Division /a / b Modulus %a mod ba % b
  • Slide 76
  • 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;
  • Slide 77
  • Integer Division - Solution To understand the solution, you need to remember your 3 rd Grade Math (really.) 7/4 = 1 (Integer Division) 7%4 = 3 (Modulus Division) 47 4 3 1 The answer: 1 remainder 3
  • Slide 78
  • 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
  • Slide 79
  • Modulus Division (cont.) Second Example: No matter what, your answers must be integers. 5/10 = 0 5%10 = 5 51010 0 0 5
  • Slide 80
  • 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.
  • Slide 81
  • Operator Precedence
  • Slide 82
  • Heres another problem. Whats 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.
  • Slide 83
  • 2003 Prentice Hall, Inc. All rights reserved. Operator Precedence Operator precedence represent rules for evaluating mathematical expressions. Every programming language has similar rules.
  • Slide 84
  • 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
  • Slide 85
  • 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;
  • Slide 86
  • Floating Point Data Types
  • Slide 87
  • 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.
  • Slide 88
  • 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
  • Slide 89
  • Numeric type ranges in Java Integers Floating point values
  • Slide 90
  • Example: Find an Average Suppose you want to determine a students average. int totalTests = 4; double average = 90+92+95+100/ totalTests;
  • Slide 91
  • 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;
  • Slide 92
  • 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.
  • Slide 93
  • 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;
  • Slide 94
  • 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.
  • Slide 95
  • 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).
  • Slide 96
  • 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.
  • Slide 97
  • 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)
  • Slide 98
  • 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
  • Slide 99
  • Introduction to Computers and Programming Lecture 5 Boolean type; if statement Professor: Evan Korth New York University
  • Slide 100
  • 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
  • Slide 101
  • div mod worksheet review
  • Slide 102
  • 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?
  • Slide 103
  • Review What happens if you go beyond a types 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 types bounds using arithmetic? Which has higher precedence: + (addition) % (modulus)
  • Slide 104
  • 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.
  • Slide 105
  • 2003 Prentice Hall, Inc. All rights reserved. Relational Operators Not Equal to!= Equal to== Less than or equal to= Less than< Greater than> MeaningOperator
  • Slide 106 b); System.out.println (a >= b); } boolVar: false boolVar: true truefalsefalsetruefalsetrue">
  • 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 ("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); } boolVar: false boolVar: true truefalsefalsetruefalsetrue
  • Slide 107
  • 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 == )
  • Slide 108
  • 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
  • Slide 109
  • 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
  • Slide 110
  • 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.
  • Slide 111
  • 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.
  • Slide 112
  • Flow Chart Basics 1 Rectangles represent statements of work. For example: System.out.println(); Diamonds (decision symbol) contain conditions flow line flow line Connector symbol
  • Slide 113
  • Control Structures
  • Slide 114
  • 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 whats executed in which order
  • Slide 115
  • 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.
  • Slide 116 = 85 ) { System.out.println( "> = 85 ) { System.out.println( "It is hot out!" ); }">
  • Another if example if ( temperature >= 85 ) { System.out.println( "It is hot out!" ); }
  • Slide 118
  • if Flow Chart print It is hot temperature >=85 true false
  • Slide 119
  • if with a twist: if else Pseudocode: if some Boolean expression is true do this otherwise do something else Example: if ( grade >= 65 ) System.out.println ( "You passed!" ); else System.out.println ( "You failed!" );
  • Slide 120
  • if/else Flow Chart grade >=60 Print You passed Print You failed TrueFalse
  • Slide 121 = 60 ) { System.out.println ( "You passed!">
  • Blocks To run several lines of code together, you must include them within a block For example: if ( grade >= 60 ) { System.out.println ( "You passed!" ); System.out.println ( "Congratulations!" ); }
  • Slide 122
  • 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
  • Slide 123
  • Common error: misplaced semi-colon Remember, Java requires that you use a semicolon to terminate a statement. A complete if statement is formed as follows: if (boolean expression) Statement or block of code; Therefore, if you place a semicolon after the conditional as in if (boolean expression); Statement or block of code; The compiler will interpret the semicolon as a null statement. In other words, nothing will happen if the expression evaluates to true and the statement of block of code will be executed whether or not the boolean expression is true.
  • Slide 124 = 65 ) { System.out.println ( "You passed!!!" ); System.out.println ( "Congratulations!" ); } else { System.out.println ("You failed!"); } System.exit (0); }">
  • 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); }
  • Slide 125
  • Introduction to Computers and Programming Lecture 6 Professor: Evan Korth New York University
  • Slide 126
  • 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
  • Slide 127
  • 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");
  • Slide 128
  • 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");
  • Slide 129 100) ? "F">
  • Java Provides a shortcut if/else operator: This is Javas only ternary operator (i.e. it takes three operands) System.out.println ( (sales > 100) ? "Federal Express" : "US Mail"); The conditional Statement. True Option False Option ? short- cut operator colo n
  • Slide 130
  • 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");
  • Slide 131 60"> 60) System.out.println("You passed but need a tutor"); else System.out.println("You failed");"> 60" title="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">
  • 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");
  • Slide 132
  • Choosing the flavor of your if When you have multiple possible branches, you can have any of the following situations: 1.You want to execute exactly one of the branches 2.You want to execute zero or one of the branches 3.You want to execute zero or more branches Which would be appropriate for each of the situations above: a)A series of if s b)A series of if / else if s ending with an else if c)A series of if / else if s ending with an else 1 c 2 b 3 a
  • Slide 133
  • 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");
  • Slide 134
  • && - 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))
  • Slide 135
  • || - 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))
  • Slide 136
  • ^ - 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))
  • Slide 137
  • 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
  • Slide 138
  • 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.
  • Slide 139
  • switch Multiple-Selection Structure Used when testing a variable or expression for EQUALITY (ie no >, =,
  • Line Continuations Pick good spots to break up a long line Break so its 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
  • Slide 147
  • 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.
  • Slide 148
  • 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 }
  • Slide 149
  • 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.
  • Slide 150
  • Introduction to Computers and Programming Lecture 7: assignment operators and introduction to while loops Instructor: Evan Korth New York University
  • Slide 151
  • 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)
  • Slide 152
  • 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)
  • Slide 153
  • Review continued What is the output of the following code fragment? int a = 100, b = 50; if ((a == 60) && (b