1 / 35

Road Map for Today

Introduction to Computers and Programming Lecture 3: Variables and Input Professor: Evan Korth New York University. Road Map for Today. Variables 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.

ahart
Download Presentation

Road Map for Today

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Computers and ProgrammingLecture 3: Variables and InputProfessor: Evan KorthNew York University

  2. Road Map for Today • Variables • 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

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

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

  5. Variables

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

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

  8. Java’s Main 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.

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

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

  11. 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 a double variable */ double price; /* Creates a character variable */ char letter; semi-colon data type identifier

  12. 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 • Should not redefine words defined elsewhere. (modified by Evan Korth)

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

  14. 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, all our variables shall be declared at the beginning of a block of code within main(). public class Sample { public static void main(String args[]) { declare variables here { or inside a nested block } } // end method main } // end class Sample

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

  16. Assignment Statements • Assignment statements enable one to initialize 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.

  17. Assignment Operator • = • Read the assignment operator as “GETS” not “EQUALS!” • This is an assignment of what’s on the right side of = to a variable on the left • eg sum = integer1 + integer2; • Read this as, “sum gets integer1 + integer2” • integer1 and integer2 are added together and stored in sum

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

  19. Good Programming Practices • 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.

  20. Revisit Errors

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

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

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

  24. Declare variables: name and type. Input first integer as a String, assign to firstNumber. Convert strings to integers. Add, place 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 Addition.java1. import2. class Addition2.1 Declare variables (name and type)3. showInputDialog4. parseInt5. Add numbers, put result in sum

  25. 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 Program output

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

  27. String firstNumber, secondNumber; 12 String firstNumber; // first string entered by user 13 String secondNumber; // second string entered by user 2.5 Another Java Application: Adding Integers • Variables • Location in memory that stores a value • Declare with name and type before use • firstNumber and secondNumber are of type String (package java.lang) • Hold strings • Variable name: any valid identifier • Declarations end with semicolons ; • Can declare multiple variables of the same type at a time • Use comma separated list • Can add comments to describe purpose of variables

  28. 15 int number1; // first number to add 16 int number2; // second number to add 17 int sum; // sum of number1 and number2 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

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

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

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

  32. 31 sum = number1 + number2; 2.5 Another Java Application: Adding Integers • Assignment statement • Calculates sum ofnumber1 and number2 (right hand side) • Uses assignment operator = to assign result to variable sum (left hand side) • Read as:sumgets the value of number1 + number2 • number1 and number2are operands

  33. 34 JOptionPane.showMessageDialog( null, "The sum is " + sum, 35 "Results", JOptionPane.PLAIN_MESSAGE ); 2.5 Another Java Application: Adding Integers • Use showMessageDialog to display results • "Thesumis"+sum • Uses the operator + to "add" the string literal "Thesumis" and sum • Concatenation of a String and another type • Results in a new string • If sum contains 117, then "Thesumis"+sum results in the new string "Thesumis117" • Note the space in "Thesumis" • More on strings later

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

  35. 2.5 Another Java Application: Adding Integers

More Related