Title: Java Variables and Expressions
1Java Variables and Expressions
- CSC160
- Professor Pepper
- (presentation adapted from Dr. Siegfried)
2Average
- On Paper Average 2 4 6
- Pay attention to your steps
3A very simple average program
- Problem write a program which can find the
average of three numbers. - Lets list the steps that our program must
perform to do this - Add up the three values
- Divide the sum by the number of values
- Print the resulting average
- Each of these steps will be a different
statement. - List the nouns to find your objects program,
value 1, value 2, value 3, sum, average -
4Noun types
Name Type Formal Name
Program ? Average1
Value 1 Int Dont need
Value 2 Int Dont need
Value 3 Int Dont need
Sum Int sum
Average Double average
5Writing Our Second Program
- Add up these values
- Divide the sum by the number of values
- Print the result
sum 2 4 6
an assignment statement
sum 2 4 6
6Assignment Statements
- Assignment statements take the form
- variable expression
Memory location where the value is stored
Combination of constants and variables
7Expressions
- Expressions combine values using one of several
operations. - The operations being used is indicated by the
operator - Addition
- - Subtraction
- Multiplication
- / Division
8Expressions Some Examples
9Writing Our Second Program
- sum 2 4 6
- Divide the sum by the number of values
- Print the result
average sum / 3
Names that describe what the values represent
10Writing Our Second Program
- sum 2 4 6
- average sum / 3
- Print the result
System.out.println(?The average is ? average)
The output method
variable name
11Writing Our Second Program
- public static void main(String args)
- --------------------
- sum 2 4 6
- average sum / 3
- System.out.println("The average is "
average) -
We still need to add a declare our variables.
This tells the computer what they are.
12Writing Our Second Program
- public class Average3
- public static void main(String args)
- int sum, average
- sum 2 4 6
- average sum / 3
- System.out.println("The average is "
average) -
Tells the computer that sum and average are
integers
13Writing Our Second Program
- public class Average3a
- public static void main(String args)
- int sum
- int average
- sum 2 4 6
- average sum / 3
- System.out.println("The average is "
average) -
We could also write this as two separate
declarations.
14Variables and Identifiers
- Variables have names we call these names
identifiers. - Identifiers identify various elements of a
program (so far the only such element are the
variables. - Some identifiers are standard (such as System)
15Identifier Rules
- An identifier must begin with a letter or an
underscore _ - Java is case sensitive upper case (capital) or
lower case letters are considered different
characters. Average, average and AVERAGE are
three different identifiers. - Numbers can also appear after the first
character. - Identifiers can be as long as you want but names
that are too long usually are too cumbersome. - Identifiers cannot be reserved words (special
words like int, main, etc.)
16Some Illegal Identifiers
17Types
type kind memory range
byte integer 1 byte -128 to 127
short integer 2 bytes -32768 to 32767
int integer 4 bytes -2147483648 to 2147483647
long integer 8 bytes -9223372036854775808 to-9223372036854775807
float floating point 4 bytes 3.40282347 x 1038 to3.40282347 x 10-45
double floating point 8 bytes 1.76769313486231570 x 10308 to 4.94065645841246544 x 10-324
char single character 2 bytes all Unicode characters
boolean true or false 1 bit
18What type to use?
- Repeat a value often ? worry about the size ?
- Float and Double imprecise ? not for big money!
19Assignment
- int number1 33
- double number2
- number2 number1
- byte?short?int?long?float?double
- char
20Dividing
- int / int ? int (even if you assign it to a
double) - float / int ? float
- int / float ? float
- Solution Cast it
- ans n / (double) m
21Math Operators PEMDAS
- add
- - subtract
- multiply
- - division
- remainder
- Example base (rate hours)
22Fancy Math
- variable variable op (expression)
- count count 1
- count count (6 / 2a 3)
- variable op expression
- count 1
- count (6 / 2a 3)
- Example
- int count 1
- count 2
- The value of count is now
- 3
23More Fancy Math
- Increment
- Decrment
- n adds 1 before executing
- n adds 1 after executing
- Example
24Characters
- Lets talk in words, not numbers!
- char single character
- Note it with single quotes (ex a, 1)
- Cant move to byte or short
- We can store single characters by writing
- char x, y
- x and y can hold one and only one character
25Character Strings
- We are usually interested in manipulating more
than one character at a time. - We can store more than one character by writing
- String s
- If we want s can hold to have some initial value,
we can write - String s Initial value"
- For now, we use character data for input and
output only.
26STRINGS
- Type String Holds text
- Enter with double quotes abc
- Really a class, so capitalize String
- Just a list of chars. Example byeString
G O O D B Y E W O R L D
0 1 2 3 4 5 6 7 8 9 0 1 2
- Start at 0
- byeString.charAt(3) is D
- byeString.length() is 13
- byeString.equals(somethingOtherString) is either
true or false - byeString.toUpperCase() is GOODBYE WORLD
- byeString.toLowerCase() is goodbye world
27Average Pgm with String
- Change the AVG program to put the average is
into a string first, and convert the string to
Uppercase using toUpperCase()
28Updated Avg Pgm
- public class Average3
- public static void main(String args)
- int sum, average
- String averageLabel The average is
- averageLabel averageLabel.toLowerCase()
- sum 2 4 6
- average sum / 3
- System.out.println(
- averageLabel average)
-
-
29Escape Characters 1
- BUT, I really want a quote inside my string!
- \ is -? abc\def -? abcdef
- \ is -? abc\def -? abcdef
- \\ is \ -? abc\def -? abc\def
-
30Escape Characters 2
- How do I get new lines and tabs?
- \n new line (go to beginning of next line)
- \r carriage return (go to beginning of this
line) - \t tab (go to next tab stop)
31Constants
- Constant doesnt change
- Why use a variable if
- ? massive changes later
- ? show meaning
- ? avoid Hard coding
- public static final int MAX_PEOPLE 20
- Capitalize by convention only -gt just do it.
32Spelling Conventions
- Name constants
- Variables start lower case
- Classes uppercase
- Word boundaries upper case (numberOfPods)
33Comments
- // -gt comment line ex // this is a comment
- / xxx / ? comment between marks ex
- / these are a bunch of comments
- xy
- that line above is meaningless /
- Space liberally
34Another Version of Average
- Lets rewrite the average program so it can find
the average any 3 numbers we try - First, make up examples
- We now need to
- Find our three values
- Add the values
- Divide the sum by 3
- Print the result
35Examples for Average
- 0 0 0 0/3 0 (Try zeroes)
- 100 -50 -29 21/3 7 (Try and -)
- 2 4 6 12/3 4 (Try normal)
36Writing Average3b
- This first step becomes
- 1.1 Find the first value
- 1.2 Find the second value
- 1.3 Find the third value
- 2. Add the values
- 3. Divide the sum by 3
- 4. Print the result
37Noun types
Name Type Formal Name
Program ? Average1
Value 1 int value1
Value 2 int value2
Value 3 int value3
Sum int sum
Average double average
38Writing Avg3 (continued)
- Since we want the computer to print out some kind
of prompt, the first step becomes - 1.1.1 Prompt the user for the first value
- 1.1.2 Read in the first value
- 1.2.1 Prompt the user for the second value
- 1.2.2 Read in the second value
- 1.3.1 Prompt the user for the third value
- 1.3.2 Read in the third value
- 2. Add the values
- 3. Divide the sum by 3
- 4. Print the result
39Writing Avg3 (continued)
- We can prompt the user with
- 1.1.1 System.out.println
- ("Enter the first value ?")
- 1.1.2 Read in the first value
- 1.2.1 System.out.println
- ("Enter the second value ?")
- 1.2.2 Read in the second value
- 1.3.1 System.out.println
- ("Enter the third value ?")
- 1.3.2 Read in the third value
- 2.Add the values
- 3. Divide the sum by 3
- 4. Print the result
40The Scanner Class
- Most programs will need some form of input.
- At the beginning, all of our input will come from
the keyboard. - To read in a value, we need to use an object
belonging to a class called Scanner - Scanner keyb new Scanner(System.in)
41Reading from the keyboard
- Once we declare keyb as Scanner, we can read
integer values by writing - variable keyb.nextInt()
42Writing the input statements in Average3b
- We can read in a value by writing
- System.out.println
- ("What is the first value\t?")
- int value1 keyb.nextInt()
- System.out.println
- ("What is the second value\t?")
- int value2 keyb.nextInt()
- System.out.println
- ("What is the third value\t?")
- int value3 keyb.nextInt()
- 2. Add the values
- 3. Divide the sum by 3
- 4. Print the result
43Writing the assignments statements in Average3b
- System.out.println
- ("What is the first value\t?")
- int value1 keyb.nextInt()
- System.out.println
- ("What is the second value\t?")
- int value2 keyb.nextInt()
- System.out.println
- ("What is the third value\t?")
- int value3 keyb.nextInt()
- sum value1 value2
- value3
- 3. Divide the sum by 3
- 4. Print the result
Adding up the three values
44Writing the assignments statements in Average3b
- System.out.println
- ("What is the first value\t?")
- int value1 keyb.nextInt()
- System.out.println
- ("What is the second value\t?")
- int value2 keyb.nextInt()
- System.out.println
- ("What is the third value\t?")
- int value3 keyb.nextInt()
- sum value1 value2 value3
- average sum / 3
- 4. Print the result
Calculating the average
45Writing the output statement in Average3b
- System.out.println
- ("What is the first value\t?")
- int value1 keyb.nextInt()
- System.out.println
- ("What is the second value\t?")
- int value2 keyb.nextInt()
- System.out.println
- ("What is the third value\t?")
- int value3 keyb.nextInt()
- sum value1 value2 value3
- average sum / 3
- System.out.println("The average is "
- average)
46import java.util.Scanner public class
Average3b public static void main(String
args) int sum, average Scanner keyb
new Scanner(System.in)
System.out.println ("What is the
first value\t?") int value1
keyb.nextInt() System.out.println
("What is the second value\t?") int
value2 keyb.nextInt()
47 System.out.println ("What is
the third value\t?") int value3
keyb.nextInt() sum value1 value2
value3 average sum / 3
System.out.println("The average is "
average)
48Another example calculating a payroll
- We are going to write a program which calculates
the gross pay for someone earning an hourly wage. - We need two pieces of information
- the hourly rate of pay
- the number of hours worked.
- We are expected to produce one output the gross
pay, which we can find by calculating - Gross pay Rate of pay Hours Worked
49Examples
Pay Rate Hours Gross
6.75 10 67.50
6.75 0 0
100 40 4000
50Our Design for payroll
- Get the inputs
- Calculate the gross pay
- Print the gross pay
1.1 Get the rate 1.2 Get the hours
We can substitute
51Developing The Payroll Program
1.1.1 Prompt the user for the rate 1.1.2 Read the
rate 1.2.1 Prompt the user for the
hours 1.2.2 Read the hours
We can substitute
- 1.1 Get the rate
- 1.2 Get the hours
- 2. Calculate the gross pay
- 3. Print the gross pay
52Coding the payroll program
- Before we code the payroll program, we recognize
that the values (rate, hours and gross) may not
necessarily be integers. - We will declare these to be double, which means
that they can have (but do not have to have)
fractional parts. - In Java, we usually declare our variables where
they first appear in the program.
53Developing The Payroll Program (continued)
- 1.1.1 Prompt the user for the rate
- 1.1.2 Read the rate
- 1.2.1 Prompt the user for the hours
- 1.2.2 Read the hours
- 2. Calculate the gross pay
- 3. Print the gross pay
System.out.println("What is your hourly pay
rate?") double rate keyb.nextDouble()
54Developing The Payroll Program (continued)
- System.out.println
- ("What is your hourly pay rate?")
- double rate keyb.nextDouble()
- 1.2.1 Prompt the user for the hours
- 1.2.2 Read the hours
- 2. Calculate the gross pay
- 3. Print the gross pay
System.out.println("How many hours did you
work?") double hours keyb.nextDouble()
55Developing The Payroll Program (continued)
- System.out.println
- ("What is your hourly pay rate?")
- double rate keyb.nextDouble()
- System.out.println
- ("How many hours did you work?")
- double hours keyb.nextDouble()
- 2. Calculate the gross pay
- 3. Print the gross pay
double gross rate hours
56Developing The Payroll Program (continued)
- System.out.println
- ("What is your hourly pay rate?")
- double rate keyb.nextDouble()
- System.out.println
- ("How many hours did you work?")
- double hours keyb.nextDouble()
- double gross rate hours
- 3. Print the gross pay
System.out.println("Your gross pay is "
gross)
57import java.util.Scanner public class Payroll
public static void main(String args)
Scanner keyb new Scanner(System.in)
System.out.println ("What is your
hourly pay rate?") double rate
keyb.nextDouble() System.out.println
("How many hours did you work?")
double hours keyb.nextDouble() double
gross rate hours System.out.println("Your
gross pay is
gross)
58- import java.util.Scanner
- public class Payroll
- / This program calculates the gross pay for
an - hourly worker
- Inputs - hourly rate and hours worked
- Output - Gross pay /
- public static void main(String args)
- Scanner keyb new Scanner(System.in)
-
- // Get the hourly rate
- System.out.println
- ("What is your hourly pay rate?")
- double rate keyb.nextDouble()
59- // Get the hours worked
- System.out.println
- ("How many hours did you work?")
- double hours keyb.nextDouble()
-
- // Calculate and display the gross pay
- double gross rate hours
- System.out.println("Your gross pay is "
- gross)
-
60Using Stepwise Refinement to Design a Program
- You should noticed that when we write a program,
we start by describing the steps that our program
must perform and we subsequently refine this into
a long series of more detailed steps until we are
writing individual steps. This is called
stepwise refinement. - Stepwise refinement is one of the most basic
methods for developing a program.
61Example A program to convert pounds to kilograms
- Our program will convert a weight expressed in
pounds into kilograms. - Our input is the weight in pounds.
- Our output is the weight in kilograms
- We also know that
- Kilograms Pounds / 2.2
62Examples for pounds to kilograms
- Weight in pounds (int) Weight in kilograms
- 0 0
- -22 -10
- 220 100
- 225 102.27
63Pounds to Kilograms Program (continued)
- Our program must
- Get the weight in pounds
- Calculate the weight in kilograms
- Print the weight in kilograms
64Pounds to Kilograms Program (continued)
- Our program must
- Get the weight in pounds
- Calculate the weight in kilograms
- Print the weight in kilograms
1.1 Prompt the user for the weight in
pounds 1.2 Read the pounds
65Pounds to Kilograms Program (continued)
- Our program must
- 1.1 Prompt the user for the weight in pounds
- 1.2 Read the pounds
- 2. Calculate the weight in kilograms
- 3. Print the weight in kilograms
System.out.println ("What is the weight
in pounds?") double lbs keyb.nextInt()
66Pounds to Kilograms Program (continued)
- System.out.println
- ("What is the weight in pounds?")
- double lbs keyb.nextInt()
- 2. Calculate the weight in kilograms
- 3. Print the weight in kilograms
double kg lbs / 2.2
67Pounds to Kilograms Program (continued)
- System.out.println
- ("What is the weight in pounds?")
- double lbs keyb.nextInt()
- double kg lbs / 2.2
- 3. Print the weight in kilograms
System.out.println("The weight is " kg
" kilograms")
68import java.util.Scanner public class
ConvertPounds // Convert pounds to
kilograms // Input - weight in pounds //
Output - weight in kilograms public static void
main(String args) Scanner keyb new
Scanner(System.in) // Get the weight in
pounds System.out.println ("What
is the weight in pounds?") double lbs
keyb.nextInt() // Calculate and display
the weight in // kilograms double kg
lbs / 2.2 System.out.println("The weight is
" kg " kilograms")
69Another Example The Area of A Rectangle
- Our program will calculate the area of a
rectangle. - Our input is the length and width.
- Our output is the area.
- We also know that
- Area Length Width
- 0 0 0
- 100 20 5
- 300 100 3
70Our Programs Steps
- Find the length and width
- Calculate the area
- Print the area
71Our Programs Steps (continued)
- Find the length and width
- Calculate the area
- Print the area
1.1 Find the length 1.2 Find the width
72Our Programs Steps (continued)
- 1.1 Find the length
- 1.2 Find the width
- 2. Calculate the area
- 3. Print the area
1.1.1 Prompt the user for the length 1.1.2 Read
the length 1.2.1 Prompt the user for the
width 1.1.2 Read the width
73Our Programs Steps (continued)
- 1.1.1 Prompt the user for the length
- 1.1.2 Read the length
- 1.2.1 Prompt the user for the width
- 1.1.2 Read the width
- 2. Calculate the area
- 3. Print the area
System.out.println("Enter the length?") double
length keyb.nextDouble()
System.out.println("Enter the width?") double
width keyb.nextDouble()
74Our Programs Steps (continued)
- System.out.println("Enter the length?")
- double length keyb.nextDouble()
-
- System.out.println("Enter the width?")
- double width keyb.nextDouble()
- 2. Calculate the area
- 3. Print the area
double area length width
75Our Programs Steps (continued)
- System.out.println("Enter the length?")
- double length keyb.nextDouble()
-
- System.out.println("Enter the width?")
- double width keyb.nextDouble()
- double area length width
- 3. Print the area
System.out.println("The area is " area)
76import java.util.Scanner public class
CalculateArea // Calculates the area of a
rectangle // Inputs - The length and width of
the rectangle // Output - The area of the
rectangle public static void main(String
args) Scanner keyb new
Scanner(System.in) // Print an
explanatory message for the user
System.out.println ("Given the width and
length of a rectangle") System.out.println
("this program calculates its area." )
77 // Get the inputs System.out.println(
"Enter the length?") double length
keyb.nextDouble() System.out.println("En
ter the width?") double width
keyb.nextDouble() // Calculate and
display the area double area length
width System.out.println("The area is "
area)
78More on Scanner
- You can read
- nextInt()
- nextLong()
- nextByte()
- nextDouble()
- next() up to next whitespace (delimiter)
- nextLine() up to \n
- useDelimiter()
- Throw in nextLine() to get down a line
79Try Scanner
- Tell the user to Type an integer and then a
word, and press Enter - Print it back to them with You typed ltthe first
number they typedgt and ltthe word they typedgt. - Then, ask for a whole line and print it back.
- See that you need to be careful with the Enter
keystroke. (Capture it with keyb.nextLine.)
80Scanner Play solution
- import java.util.Scanner
- public class ScannerPlay
-
- public static void main(String args)
-
- Scanner keyb new Scanner(System.in)
- System.out.println
- ("Type an integer and then a word, and
press Enter") - int number1 keyb.nextInt()
- String word1 keyb.next()
- System.out.println("You typed " number1
" and " word1 ".") - System.out.println("Type something else
and Enter") - keyb.nextLine() // skip a line
- String line1 keyb.nextLine()
- System.out.println("You typed " line1)
-