Java Variables and Expressions CSC160 Professor Pepper (presentation adapted from Dr. Siegfried)

Slides:



Advertisements
Similar presentations
Begin Java Pepper. Objectives What is a program? Learn the basics of your programming tool: BlueJ Write a first Java program and see it run Make some.
Advertisements

1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
Variables Pepper. Variable A variable –box –holds a certain type of value –value inside the box can change Example –A = 2B+1 –Slope = change in y / change.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
CIS 234: Using Data in Java Thanks to Dr. Ralph D. Westfall.
Declaring Variables You must first declare a variable before you can use it! Declaring involves: – Establishing the variable’s spot in memory – Specifying.
CMT Programming Software Applications
Mathematical Operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming in.
Introduction to Computer Programming Looping Around Loops I: Counting Loops.
Introduction to Computer Programming Decisions If/Else Booleans.
Scanner Pepper With credits to Dr. Siegfried. The Scanner Class Most programs will need some form of input. At the beginning, all of our input will come.
Lecture 4 Types & Expressions COMP1681 / SE15 Introduction to Programming.
Introduction to Computer Programming Decisions, Decisions: Boolean Expressions and Selection.
Introduction to Computer Programming Loops N Decisions If/Else Counting Loops.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
© 2006 Pearson Addison-Wesley. All rights reserved2-1 Console Input Using the Scanner Class Starting with version 5.0, Java includes a class for doing.
Introduction to Computer Programming CSC171 – 001 Getting Started – Chapters 1 & 2 Professor Pepper (presentation adapted from Dr. Siegfried)
Scanner & Stepwise Refinement Pepper With credit to Dr. Siegfried.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
Week 2 - Friday.  What did we talk about last time?  Data representation  Binary numbers  Types  int  boolean  double  char  String.
Expressions, Data Conversion, and Input
CSC172 Intro Pepper. Goals Reminder of what a class is How to create and use classes How to design classes How to think in terms of objects How to comment.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Java Data Types. Primitive Data Types Java has 8 primitive data types: – char: used to store a single character eg. G – boolean: used to store true or.
Chapter 2 Elementary Programming
Constants Numeric Constants Integer Constants Floating Point Constants Character Constants Expressions Arithmetic Operators Assignment Operators Relational.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
A First Look at Java Chapter 2 1/29 & 2/2 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals. Procedural Constructs.
CHAPTER 4 GC 101 Data types. DATA TYPES  For all data, assign a name (identifier) and a data type  Data type tells compiler:  How much memory to allocate.
FUNDAMENTALS 2 CHAPTER 2. OPERATORS  Operators are special symbols used for:  mathematical functions  assignment statements  logical comparisons 
Chapter 2 Variables.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Variables and Types Java Part 3. Class Fields  Aka member variable, field variable, instance variable, class variable.  These are the descriptors of.
Computer Programming with Java Chapter 2 Primitive Types, Assignment, and Expressions.
Java – Variables and Constants By: Dan Lunney. Declaring Variables All variables must be declared before they can be used A declaration takes the form:
Chapter 2 Console Input and Output Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Slides prepared by Rose Williams, Binghamton University Console Input and Output.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Elementary Programming.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
Fundamentals 2 1. Programs and Data Most programs require the temporary storage of data. The data to be processed is stored in a temporary storage in.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Chapter 2 Basic Computation
Elementary Programming
CSC 1051 – Data Structures and Algorithms I
Multiple variables can be created in one declaration
Variables, Expressions, and IO
Java Programming: From Problem Analysis to Program Design, 4e
IDENTIFIERS CSC 111.
Introduction to C++ Programming
مساق: خوارزميات ومبادئ البرمجة الفصل الدراسي الثاني 2016/2015
Chapter 2 Edited by JJ Shepherd
MSIS 655 Advanced Business Applications Programming
Fundamentals 2.
Chapter 2: Java Fundamentals
Introduction to Computer Programming
elementary programming
Primitive Types and Expressions
Unit 3: Variables in Java
Presentation transcript:

Java Variables and Expressions CSC160 Professor Pepper (presentation adapted from Dr. Siegfried)

Average On Paper: Average Pay attention to your steps

A very simple average program Problem – write a program which can find the average of three numbers. Let’s 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

Noun types NameTypeFormal Name Program?Average1 Value 1IntDon’t need Value 2IntDon’t need Value 3IntDon’t need SumIntsum AverageDoubleaverage

Writing Our Second Program Add up these values Divide the sum by the number of values Print the result sum = ; an assignment statement

Assignment Statements Assignment statements take the form: variable = expression Memory location where the value is stored Combination of constants and variables

Expressions Expressions combine values using one of several operations. The operations being used is indicated by the operator: +Addition -Subtraction *Multiplication /Division

Expressions – Some Examples * value x / y

Writing Our Second Program sum = ; Divide the sum by the number of values Print the result average = sum / 3; Names that describe what the values represent

Writing Our Second Program sum = average = sum / 3; Print the result System.out.println(″The average is ″ + average); The output method variable name

Writing Our Second Program public static void main(String[] args) { sum = ; 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.

Writing Our Second Program public class Average3 { public static void main(String[] args) { int sum, average; sum = ; average = sum / 3; System.out.println("The average is " + average); } Tells the computer that sum and average are integers

Writing Our Second Program public class Average3a { public static void main(String[] args) { int sum; int average; sum = ; average = sum / 3; System.out.println("The average is " + average); } We could also write this as two separate declarations.

Variables 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 )

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

Some Illegal Identifiers timeAndAHalf & is not allowed time&ahalf fourTimesFive * is not allowed four*five times2 or twoTimes Cannot begin with a number 2times myAge Blanks are not allowed my age Suggested Identifier ReasonIllegal Identifier

Types typekindmemoryrange byteinteger1 byte-128 to 127 shortinteger2 bytes to intinteger4 bytes to longinteger8 bytes to floatfloating point4 bytes± x to ± x doublefloating point8 bytes± x to ± x charsingle character 2 bytesall Unicode characters booleantrue or false1 bit

What type to use? Repeat a value often  worry about the size Float and Double imprecise  not for big money!

Assignment int number1 = 33; double number2; number2 = number1; byte  short  int  long  float  double char

Dividing int / int  int (even if you assign it to a double) float / int  float int / float  float Solution: Cast it ans = n / (double) m

Math Operators & PEMDAS + add - subtract * multiply - division % remainder Example: base + (rate * hours)

Fancy 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

More Fancy Math Increment ++ Decrment – ++n adds 1 before executing n++ adds 1 after executing Example:

Characters Let’s talk in words, not numbers! char = single character Note it with single quotes (ex: ‘a’, ‘1’) Can’t move to byte or short We can store single characters by writing: charx, y; –x and y can hold one and only one character

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

STRINGS Type : String Holds text Enter with double quotes “abc” Really a class, so capitalize String Just a list of chars. Example byeString: GOODBYEWORLD 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

Average Pgm with String Change the AVG program to put “the average is” into a string first, and convert the string to Uppercase using toUpperCase()

Updated Avg Pgm public class Average3 { public static void main(String[] args) { int sum, average; String averageLabel = “The average is “; averageLabel = averageLabel.toLowerCase(); sum = ; average = sum / 3; System.out.println( averageLabel + average); }

Escape Characters 1 BUT, I really want a quote inside my string! \” is “ -  “abc\”def” -  abc”def \’ is ‘ -  “abc\’def” -  abc’def \\ is \ -  “abc\def” -  abc\def

Escape 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)

Constants Constant doesn’t 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 -> just do it.

Spelling Conventions Name constants Variables start lower case Classes uppercase Word boundaries upper case (numberOfPods)

Comments // -> comment line ex: // this is a comment /* xxx */  comment between marks ex: /* these are a bunch of comments x=y; that line above is meaningless */ Space liberally

Another Version of Average Let’s rewrite the average program so it can find the average any 3 numbers we try: First, make up examples We now need to: 1.Find our three values 2.Add the values 3.Divide the sum by 3 4.Print the result

Examples for Average = 0/3 = 0 (Try zeroes) = 21/3 = 7 (Try + and -) = 12/3 = 4 (Try normal)

Writing Average3b This first step becomes: 1.1Find the first value 1.2Find the second value 1.3Find the third value 2.Add the values 3.Divide the sum by 3 4.Print the result

Noun types NameTypeFormal Name Program?Average1 Value 1intvalue1 Value 2intvalue2 Value 3intvalue3 Sumintsum Averagedoubleaverage

Writing Avg3 (continued) Since we want the computer to print out some kind of prompt, the first step becomes: 1.1.1Prompt the user for the first value 1.1.2Read in the first value Prompt the user for the second value 1.2.2Read in the second value 1.3.1Prompt the user for the third value 1.3.2Read in the third value 2.Add the values 3.Divide the sum by 3 4.Print the result

Writing Avg3 (continued) We can prompt the user with: System.out.println ("Enter the first value ?"); 1.1.2Read in the first value System.out.println ("Enter the second value ?"); 1.2.2Read in the second value System.out.println ("Enter the third value ?"); 1.3.2Read in the third value 2.Add the values 3.Divide the sum by 3 4.Print the result

The 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);

Reading from the keyboard Once we declare keyb as Scanner, we can read integer values by writing: variable = keyb.nextInt();

Writing 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

Writing 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

Writing 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

Writing 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);

import 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();

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); }

Another 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

Examples Pay RateHoursGross $6.7510$67.50 $ $10040$4000

Our Design for payroll 1.Get the inputs 2.Calculate the gross pay 3.Print the gross pay 1.1 Get the rate 1.2 Get the hours We can substitute:

Developing The Payroll Program 1.1 Get the rate 1.2 Get the hours 2.Calculate the gross pay 3.Print the gross pay 1.1.1Prompt the user for the rate 1.1.2Read the rate 1.2.1Prompt the user for the hours 1.2.2Read the hours We can substitute

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

Developing The Payroll Program (continued) 1.1.1Prompt the user for the rate 1.1.2Read the rate 1.2.1Prompt the user for the hours 1.2.2Read 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();

Developing The Payroll Program (continued) System.out.println ("What is your hourly pay rate?"); double rate = keyb.nextDouble(); 1.2.1Prompt the user for the hours 1.2.2Read 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();

Developing 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;

Developing 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);

import 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); }

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();

// 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); }

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

Example – 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

Examples for pounds to kilograms Weight in pounds (int)Weight in kilograms

Pounds to Kilograms Program (continued) Our program must: 1.Get the weight in pounds 2.Calculate the weight in kilograms 3.Print the weight in kilograms

Pounds to Kilograms Program (continued) Our program must: 1.Get the weight in pounds 2.Calculate the weight in kilograms 3.Print the weight in kilograms 1.1 Prompt the user for the weight in pounds 1.2Read the pounds

Pounds 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();

Pounds 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;

Pounds 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");

import 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"); }

Another 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 * = 20 * = 100 * 3

Our Program’s Steps 1.Find the length and width 2.Calculate the area 3.Print the area

Our Program’s Steps (continued) 1.Find the length and width 2.Calculate the area 3.Print the area 1.1 Find the length 1.2 Find the width

Our Program’s Steps (continued) 1.1 Find the length 1.2 Find the width 2. Calculate the area 3. Print the area Prompt the user for the length Read the length Prompt the user for the width Read the width

Our Program’s Steps (continued) Prompt the user for the length Read the length Prompt the user for the width 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();

Our Program’s 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;

Our Program’s 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);

import 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." );

// Get the inputs System.out.println("Enter the length?"); double length = keyb.nextDouble(); System.out.println("Enter the width?"); double width = keyb.nextDouble(); // Calculate and display the area double area = length * width; System.out.println("The area is " + area); }

More 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

TryScanner Tell the user to “Type an integer and then a word, and press Enter” Print it back to them with “You typed and.” 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.)

Scanner 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); }