Variables - New York University
Download
Report
Transcript Variables - New York University
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
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?
Review
• What’s wrong with this program?
public class Welcome
{
public static void main( String args[] )
{
JOptionPane.showMessageDialog(
null, "Welcome to Java!" );
System.exit( 0 );
} // end method main
} // end class Welcome
Variables
Variables
• Variable: a small piece or “chunk” of data.
• Variables enable one to temporarily store data
within a program, and are therefore very useful.
Note: variables are not persistent. When you exit
your program, the data is deleted. To create
persistent data, you must store it to a file system.
Data Types
• Every variable must have two things: a data type and a
name.
• Data Type: defines the kind of data the variable can hold.
– For example, can this variable hold numbers? Can it
hold text?
– Java supports several different data types. We are only
going to look at a few today.
Java’s (primitive) Data Types
• integers: the simplest data type in Java. Used to
hold positive and negative whole numbers, e.g. 5,
25, -777, 1. (Java has several different integer
types)
• Floating point: Used to hold fractional or decimal
values, e.g. 3.14, 10.25. (Java has two different
floating point types)
• chars: Used to hold individual characters, e.g. 'c',
'e', '1', '\n'
• boolean: Used for logic.
• We will explore each one in detail later this
semester.
Bucket Analogy
• It is useful to think of a variable as a bucket of
data.
• The bucket has a unique name, and can only hold
certain kinds of data.
200
balance
balance is a variable
containing the value
200, and can contain
only integers.
Memory Concepts
• Variable names correspond to locations in the
computer’s primary memory.
• Every variable has a name, a type and a value.
• When a value is placed in a memory location the
value replaces the previous value in that location
(called destructive read-in)
• A variable’s value can just be used and not
destroyed (called non-destructive read-out)
Variable Declaration
• Before you use a variable, you must declare it. (Not all
languages require this, but Java certainly does.)
• Examples:
/* Creates an integer variable */
int number;
/* Creates two double variables */
double price, tax;
/* Creates a character variable */
char letter;
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
• Try not to redefine identifiers used elsewhere.
2003 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
Reserved Words (added to previous definition of identifiers)
• Certain words have special meaning in Java and cannot be
used as identifiers. These words are called reserved words.
• So far we have seen the following reserved words:
–
–
–
–
–
–
int
public
import
static
void
class
• We will see a complete list of reserved words soon.
• Use of the words null, true and false is also prohibited.
Important Point about Declarations
• In Java you can declare variables at many different places
in the program. They have different meaning and scope
depending on where they are declared. For now, we will
declare all our variables at the beginning of main().
public class Sample {
public static void main(String args[])
{
declare variables here
executable statements here
} // end method main
} // end class Sample
Example 1: Basic Arithmetic
/* Illustrates Integer Variables */
public class Sample {
public static void main(String args[])
Variable Declarations
{
int x;
Variable Name
int y;
int z;
semicolon
Data Type
x = 5;
y = 10;
z = x + y;
Assignment Statements
System.out.println ("x:
System.out.println ("y:
System.out.println ("z:
} // end method main
} // end class Sample
" + x);
" + y);
" + z);
x:
y:
z:
5
10
15
Assignment Statements
• Assignment statements enable one to assign (initial or not)
values to variables or perform basic arithmetic.
x = 5;
y = 10;
z = x + y;
• Here, we simply initialize x and y and store their sum
within the variable z.
Note: If you forget to initialize your variables, the
variable may contain any value. This is referred to as a
garbage value. Hence, always initialize your variables!
Java enforces this rule; but, not all languages do.
Assignment Operator
• =
• Read the assignment operator as “GETS” not
“EQUALS!”
• This is an assignment of what’s on the right side
of = to a variable on the left
• eg sum = integer1 + integer2;
– Read this as, “sum gets integer1 + integer2”
– integer1 and integer2 are added together and stored in sum
Printing Variables
• To print a variable, use the System.out.print or
System.out.println statement as you would for a
string.
System.out.print (x);
System.out.println (x);
System.out.println ("x:
" + x);
Here the “addition” that
is performed is string
concatenation.
Initialization
• When you declare a primitive variable, you do not
know the value stored in that variable until you
place something there. The language specification
does not guarantee any initial value.
• Until the user initializes the value, the value stored
in that memory is called a garbage value.
• Java will not allow you to use the garbage value in
a calculation or for output. If it is possible that a
variable has not been initialized when you try to
use it, you will get a compilation error.
• So you must initialize the variable before you use
it on the right hand side of a calculation or output
it to the screen.
Good Programming Style
Choose meaningful variable names to make your
program more readable. For example, use income,
instead of num.
Stick to lower-case variable names. For example, use
income, instead of INCOME. Variables that are all
capitals usually indicate a constant (more on this
soon.)
Use "proper case" for all words after the first in a
variable name. For example, instead of
totalcommissions, use totalCommissions.
Avoid redefining identifiers previously defined in the
Java API.
Revisit Errors
Syntax Errors
• Caused when the compiler cannot recognize a
statement.
• These are violations of the language
• The compiler normally issues an error message to
help the programmer locate and fix it
• Also called compile errors or compile-time errors.
• For example, if you forget a semi-colon, you will
get a syntax error.
Run-time Errors
• The compiler cannot pick up on runtime errors.
Therefore they happen at runtime.
• Runtime errors fall into two categories.
– Fatal runtime errors: These errors cause your program to
crash.
– Logic errors: The program can run but the results are not
correct.
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
2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
25
// Fig. 2.9: Addition.java
// Addition program that displays the sum of two numbers.
// Java packages
import javax.swing.JOptionPane;
Outline
Addition.java
// program uses JOptionPane
1. import
public class Addition {
name and
// main method begins executionDeclare
of Javavariables:
application
public static void main( String args[] )
{
String firstNumber;
// first string entered by user
String secondNumber; // second string entered by user
int number1;
int number2;
int sum;
type.
// first number to add
Input
first integer
// second
number
to add as a String,
// sum to
offirstNumber.
number1 and number2
2.1 Declare variables
(name and type)
assign
// read in first number from user as a String
firstNumber = JOptionPane.showInputDialog( "Enter first integer" );
// read in second number from user as a String
secondNumber =
JOptionPane.showInputDialog( "Enter second integer" );
2. class Addition
3.
showInputDialog
4. parseInt
5. Add numbers, put
result in sum
Convert strings to integers.
// convert numbers from type StringAdd,
to type
placeint
result
number1 = Integer.parseInt( firstNumber );
number2 = Integer.parseInt( secondNumber );
// add numbers
sum = number1 + number2;
in sum.
2003 Prentice Hall, Inc.
All rights reserved.
26
33
34
35
36
37
38
39
40
41
// display result
JOptionPane.showMessageDialog( null, "The sum is " + sum,
"Results", JOptionPane.PLAIN_MESSAGE );
System.exit( 0 );
Outline
// terminate application with window
} // end method main
} // end class Addition
Program output
2003 Prentice Hall, Inc.
All rights reserved.
27
2.5
5
Another Java Application: Adding
Integers
import javax.swing.JOptionPane;
// program uses JOptionPane
– Location of JOptionPane for use in the program
7
public class Addition {
– Begins public class Addition
• Recall that file name must be Addition.java
– Lines 10-11: main
12
13
String firstNumber;
String secondNumber;
// first string entered by user
// second string entered by user
– Declaration
• firstNumber and secondNumber are variables
2003 Prentice Hall, Inc. All rights reserved.
28
2.5
12
13
Another Java Application: Adding
Integers
String firstNumber;
String secondNumber;
// first string entered by user
// 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 ;
String firstNumber, secondNumber;
– Can declare multiple variables of the same type at a time
– Use comma separated list
– Can add comments to describe purpose of variables
2003 Prentice Hall, Inc. All rights reserved.
29
2.5
15
16
17
Another Java Application: Adding
Integers
int number1;
int number2;
int sum;
// first number to add
// second number to add
// sum of number1 and number2
– 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
2003 Prentice Hall, Inc. All rights reserved.
30
2.5
20
Another Java Application: Adding
Integers
firstNumber = JOptionPane.showInputDialog( "Enter first integer" );
– 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
2003 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
31
2.5
20
Another Java Application: Adding
Integers
firstNumber = JOptionPane.showInputDialog( "Enter first integer" );
– 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" )
2003 Prentice Hall, Inc. All rights reserved.
32
2.5
23
24
Another Java Application: Adding
Integers
secondNumber =
JOptionPane.showInputDialog( "Enter second integer" );
– Similar to previous statement
• Assigns variable secondNumber to second integer input
27
28
number1 = Integer.parseInt( firstNumber );
number2 = Integer.parseInt( secondNumber );
– 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
2003 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
33
2.5
31
Another Java Application: Adding
Integers
sum = number1 + number2;
– 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
2003 Prentice Hall, Inc. All rights reserved.
34
2.5
34
35
Another Java Application: Adding
Integers
JOptionPane.showMessageDialog( null, "The sum is " + sum,
"Results", JOptionPane.PLAIN_MESSAGE );
– 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
2003 Prentice Hall, Inc. All rights reserved.
35
2.5
34
35
Another Java Application: Adding
Integers
JOptionPane.showMessageDialog( null, "The sum is " + sum,
"Results", JOptionPane.PLAIN_MESSAGE );
– 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
2003 Prentice Hall, Inc. All rights reserved.
36
2.5
Another Java Application: Adding
Integers
Messa g e d ia lo g typ e
Ic o n
Desc rip tio n
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
Displays a dialog that simply contains a
message, with no icon.
Fig. 2.12 JOptionPane c o nsta nts fo r m essa g e d ia lo g s.
2003 Prentice Hall, Inc. All rights reserved.
no icon