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

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

  • View
    230

  • Download
    1

Embed Size (px)

Citation preview

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

Introduction to Computers and Programming

Lecture 3: Variables and Input

Professor: Evan KorthNew York University

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

Road Map for Today

• Variables– int

– Strings

• Getting input from a user using JOptionPane

• Revisit: Types of errors

• Reading – Liang 5: Chapter 2, Sections 2.1 – 2.5, 2.14, 2.19

– Liang 6: Chapter 2, Sections 2.1 – 2.5, 2.11, 2.15

– Liang 7: Chapter 2, Sections 2.1 – 2.5, 2.14, 2.16

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

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?

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

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

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

Variables

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

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.

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

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.

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

Java’s (primitive) Data Types

• integers: the simplest data type in Java. Used to hold positive and negative whole numbers, e.g. 5, 25, -777, 1. (Java has several different integer types)

• Floating point: Used to hold fractional or decimal values, e.g. 3.14, 10.25. (Java has two different floating point types)

• chars: Used to hold individual characters, e.g. 'c', 'e', '1', '\n'

• boolean: Used for logic.• We will explore each one in detail later this

semester.

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

Bucket Analogy

• It is useful to think of a variable as a bucket of data.

• The bucket has a unique name, and can only hold certain kinds of data.

balance

200

balance is a variablecontaining the value200, and can containonly integers.

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

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)

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

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

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

2003 Prentice Hall, Inc. All rights reserved.

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)

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

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.

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

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

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

Example 1: Basic Arithmetic

/* Illustrates Integer Variables */public class Sample {

public static void main(String args[]) {

int x;int y;int z;

x = 5;y = 10;z = x + y;

System.out.println ("x: " + x);System.out.println ("y: " + y);System.out.println ("z: " + z);

} // end method main} // end class Sample

Variable Declarations

Data Type

Variable Name

Assignment Statements

x: 5y: 10z: 15

semicolon

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

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.

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

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

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

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.

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

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.

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

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.

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

Revisit Errors

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

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.

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

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.

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

2003 Prentice Hall, Inc. All rights reserved.

24

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

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

2003 Prentice Hall, Inc.All rights reserved.

Outline25

Addition.java

1. import

2. class Addition

2.1 Declare variables (name and type)

3. showInputDialog

4. parseInt

5. Add numbers, put result in sum

1 // Fig. 2.9: Addition.java2 // Addition program that displays the sum of two numbers.3 4 // Java packages 5 import javax.swing.JOptionPane; // program uses JOptionPane6 7 public class Addition {8 9 // main method begins execution of Java application10 public static void main( String args[] )11 {12 String firstNumber; // first string entered by user 13 String secondNumber; // second string entered by user14 15 int number1; // first number to add 16 int number2; // second number to add 17 int sum; // sum of number1 and number218 19 // read in first number from user as a String 20 firstNumber = JOptionPane.showInputDialog( "Enter first integer" );21 22 // read in second number from user as a String 23 secondNumber = 24 JOptionPane.showInputDialog( "Enter second integer" );25 26 // convert numbers from type String to type int27 number1 = Integer.parseInt( firstNumber ); 28 number2 = Integer.parseInt( secondNumber ); 29 30 // add numbers 31 sum = number1 + number2;32

Declare variables: name and type.

Input first integer as a String, assign to firstNumber.

Add, place result in sum.

Convert strings to integers.

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

2003 Prentice Hall, Inc.All rights reserved.

Outline26

Program output

33 // display result 34 JOptionPane.showMessageDialog( null, "The sum is " + sum,35 "Results", JOptionPane.PLAIN_MESSAGE ); 36 37 System.exit( 0 ); // terminate application with window38 39 } // end method main40 41 } // end class Addition

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

2003 Prentice Hall, Inc. All rights reserved.

27

2.5 Another Java Application: Adding Integers

– Location of JOptionPane for use in the program

– Begins public class Addition• Recall that file name must be Addition.java

– Lines 10-11: main

– Declaration• firstNumber and secondNumber are variables

5 import javax.swing.JOptionPane; // program uses JOptionPane

7 public class Addition {

12 String firstNumber; // first string entered by user 13 String secondNumber; // second string entered by user

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

2003 Prentice Hall, Inc. All rights reserved.

28

2.5 Another Java Application: Adding Integers

– Variables• Location in memory that stores a value

– Declare with name and type before use

• firstNumber and secondNumber are of type String (package java.lang)

– Hold strings

• Variable name: any valid identifier

• Declarations end with semicolons ;

– Can declare multiple variables of the same type at a time

– Use comma separated list

– Can add comments to describe purpose of variables

String firstNumber, secondNumber;

12 String firstNumber; // first string entered by user 13 String secondNumber; // second string entered by user

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

2003 Prentice Hall, Inc. All rights reserved.

29

2.5 Another Java Application: Adding Integers

– Declares variables number1, number2, and sum of type int• int holds integer values (whole numbers): i.e., 0, -4, 97• Types float and double can hold decimal numbers

• Type char can hold a single character: i.e., 'x', '$', '\n', '7'

• Primitive types

15 int number1; // first number to add 16 int number2; // second number to add 17 int sum; // sum of number1 and number2

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

2003 Prentice Hall, Inc. All rights reserved.

30

2.5 Another Java Application: Adding Integers

– Reads String from the user, representing the first number to be added

• Method JOptionPane.showInputDialog displays the following:

• Message called a prompt - directs user to perform an action

• Argument appears as prompt text

• If you click Cancel, error occurs

20 firstNumber = JOptionPane.showInputDialog( "Enter first integer" );

(modified by Evan Korth)

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

2003 Prentice Hall, Inc. All rights reserved.

31

2.5 Another Java Application: Adding Integers

– Result of call to showInputDialog given to firstNumber using assignment operator =

• Assignment statement

• = binary operator - takes two operands

– Expression on right evaluated and assigned to variable on left

• Read as: firstNumber gets value of JOptionPane.showInputDialog( "Enter first integer" )

20 firstNumber = JOptionPane.showInputDialog( "Enter first integer" );

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

2003 Prentice Hall, Inc. All rights reserved.

32

2.5 Another Java Application: Adding Integers

– Similar to previous statement• Assigns variable secondNumber to second integer input

– Method Integer.parseInt• Converts String argument into an integer (type int)

– Class Integer in java.lang• Integer returned by Integer.parseInt is assigned to

variable number1 (line 27)

– Remember that number1 was declared as type int– If a non-integer value was entered an error will occur

• Line 28 similar

23 secondNumber = 24 JOptionPane.showInputDialog( "Enter second integer" );

27 number1 = Integer.parseInt( firstNumber ); 28 number2 = Integer.parseInt( secondNumber );

(modified by Evan Korth)

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

2003 Prentice Hall, Inc. All rights reserved.

33

2.5 Another Java Application: Adding Integers

– Assignment statement• Calculates sum of number1 and number2 (right hand side)

• Uses assignment operator = to assign result to variable sum (left hand side)

• Read as: sum gets the value of number1 + number2• number1 and number2 are operands

31 sum = number1 + number2;

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

2003 Prentice Hall, Inc. All rights reserved.

34

2.5 Another Java Application: Adding Integers

– Use showMessageDialog to display results

– "The sum is " + sum• Uses the operator + to "add" the string literal "The sum is"

and sum• Concatenation of a String and another type

– Results in a new string

• If sum contains 117, then "The sum is " + sum results in the new string "The sum is 117"

• Note the space in "The sum is "• More on strings later

34 JOptionPane.showMessageDialog( null, "The sum is " + sum,35 "Results", JOptionPane.PLAIN_MESSAGE );

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

2003 Prentice Hall, Inc. All rights reserved.

35

2.5 Another Java Application: Adding Integers

– Different version of showMessageDialog• Requires four arguments (instead of two as before)

• First argument: null for now

• Second: string to display

• Third: string in title bar

• Fourth: type of message dialog with icon

– Line 35 no icon: JOptionPane.PLAIN_MESSAGE

34 JOptionPane.showMessageDialog( null, "The sum is " + sum,35 "Results", JOptionPane.PLAIN_MESSAGE );

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

2003 Prentice Hall, Inc. All rights reserved.

36

2.5 Another Java Application: Adding Integers

Message dialog type Icon Description

JOptionPane.ERROR_MESSAGE

Displays a dialog that indicates an error to the user.

JOptionPane.INFORMATION_MESSAGE

Displays a dialog with an informational message to the user. The user can simply dismiss the dialog.

JOptionPane.WARNING_MESSAGE

Displays a dialog that warns the user of a potential problem.

JOptionPane.QUESTION_MESSAGE

Displays a dialog that poses a question to the user. This dialog normally requires a response, such as clicking on a Yes or a No button.

JOptionPane.PLAIN_MESSAGE no icon Displays a dialog that simply contains a

message, with no icon. Fig. 2.12 JOptionPane constants for message dialogs.