Download presentation
Presentation is loading. Please wait.
2
Introduction to Computers and Programming Lecture 3: Variables and Input Professor: Evan Korth New York University
3
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
4
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?
5
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
6
Variables
7
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.
8
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.
9
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.
10
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.
11
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)
12
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
13
2003 Prentice Hall, Inc. All rights reserved. 12 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 Should not redefine words defined elsewhere. (modified by Evan Korth )
14
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.
15
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
16
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
17
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.
18
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
19
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.
20
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.
21
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.
22
Revisit Errors
23
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.
24
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.
25
2003 Prentice Hall, Inc. All rights reserved. 24 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
26
2003 Prentice Hall, Inc. All rights reserved. Outline 25 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.
27
2003 Prentice Hall, Inc. All rights reserved. Outline 26 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
28
2003 Prentice Hall, Inc. All rights reserved. 27 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
29
2003 Prentice Hall, Inc. All rights reserved. 28 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
30
2003 Prentice Hall, Inc. All rights reserved. 29 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
31
2003 Prentice Hall, Inc. All rights reserved. 30 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)
32
2003 Prentice Hall, Inc. All rights reserved. 31 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" );
33
2003 Prentice Hall, Inc. All rights reserved. 32 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)
34
2003 Prentice Hall, Inc. All rights reserved. 33 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;
35
2003 Prentice Hall, Inc. All rights reserved. 34 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 );
36
2003 Prentice Hall, Inc. All rights reserved. 35 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 );
37
2003 Prentice Hall, Inc. All rights reserved. 36 2.5Another Java Application: Adding Integers
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.