CompSci 230 S Programming Techniques

Slides:



Advertisements
Similar presentations
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
Advertisements

ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
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;
Topic 11 Scanner object, conditional execution Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
Expressions, Data Conversion, and Input
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
CPS120: Introduction to Computer Science Operations Lecture 9.
Operators Precedence - Operators with the highest precedence will be executed first. Page 54 of the book and Appendix B list C's operator precedence. Parenthesis.
FUNDAMENTALS 2 CHAPTER 2. OPERATORS  Operators are special symbols used for:  mathematical functions  assignment statements  logical comparisons 
CHAPTER 5 GC 101 Input & Output 1. INTERACTIVE PROGRAMS  We have written programs that print console output, but it is also possible to read input from.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Boolean expressions, part 1: Compare operators. Compare operators Compare operators compare 2 numerical values and return a Boolean (logical) value A.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
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.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
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.
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
Building Java Programs
Expressions.
Chapter 2 Basic Computation
Chapter 7: Expressions and Assignment Statements
Lecture 3 Java Operators.
Expressions.
University of Central Florida COP 3330 Object Oriented Programming
PowerPoint Presentation Authors of Exposure Java
University of Central Florida COP 3330 Object Oriented Programming
Relational Operations
Chapter 7: Expressions and Assignment Statements
Expressions An expression is a portion of a C++ statement that performs an evaluation of some kind Generally requires that a computation or data manipulation.
Data Conversion & Scanner Class
Assignment and Arithmetic expressions
Primitive Data, Variables, Loops (Maybe)
User input We’ve seen how to use the standard output buffer
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 2 Basic Computation
Topic 11 Scanner object, conditional execution
Operators and Expressions
Lecture 3 Expressions Richard Gesick.
Winter 2018 CISC101 11/22/2018 CISC101 Reminders
Chapter 2: Basic Elements of Java
Building Java Programs
Building Java Programs
Fundamentals 2.
Building Java Programs
Expressions and Assignment
Building Java Programs
Building Java Programs
Chapter 2: Java Fundamentals
Building Java Programs
Data Types and Expressions
Building Java Programs
Building Java Programs
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Building Java Programs
Building Java Programs
Primitive Types and Expressions
Building Java Programs
CSC 1051 – Data Structures and Algorithms I
Building Java Programs
Building Java Programs
Data Types and Expressions
Building Java Programs
Data Types and Expressions
Introduction to Python
Presentation transcript:

CompSci 230 S2 2017 Programming Techniques Expressions

Today’s Agenda Topics: Reading: Prompting the User for Input Expressions Arithmetic Expressions Relational Expressions Logical Expressions Reading: Java how to program Late objects version (D & D) Chapter 2 & Chapter 3 The Java Tutorials Lesson: Language Basics: Operators, Expressions, Statements, and Blocks https://docs.oracle.com/javase/tutorial/java/nutsandbolts/index.html Welcome to Java for Python Programmers http://interactivepython.org/courselib/static/java4python/index.html Lecture03

1.Prompting the User for Input A Java program can obtains inputs from the console through the keyboard. The variable named System.in represents the keyboard There is a lot of work that the computer must do to read in a number The Java programming language provides a collection of methods stored in the Scanner class that perform read operations.   Lecture03

1.Prompting the User for Input Declaring and Creating a Scanner L03Code.java Importing the Scanner class definition Scanner is in a package named java.util To use Scanner, you must place the above line at the top of your program (before the public class header). Constructing a Scanner object to read console input: The new keyword creates an object. Standard input object, System.in, enables applications to read bytes of data typed by the user. Scanner object translates these bytes into types that can be used in a program. import java.util.Scanner; Scanner console = new Scanner(System.in); Lecture03

1.Prompting the User for Input Scanner methods After having constructed the Scanner object named in: Display a prompt: - A message telling the user what input to type. Use one of the following methods to read from the keyboard: Each method waits until the user presses Enter. The value typed is returned. You must save (store) the number read in a variable with an assignment statement Method Description nextInt() reads a token of user input as an int nextDouble() reads a token of user input as a double next() reads a token of user input as a String nextLine() reads a line of user input as a String System.out.print("How old are you? "); // prompt int age = console.nextInt(); System.out.println("You'll be 40 in " + (40 - age) + " years."); Lecture03

1.Prompting the User for Input Example 1 Summarizes the programming steps to read in a number: 1. import the Scanner class 2. Construct a Scanner object 3. Display a prompt message 3. Define a variable to receive the value 4. Read input How old are you? 65 65... That's quite old! import java.util.Scanner; public class L02Code { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("How old are you? "); int age = console.nextInt(); System.out.println(age + "... That's quite old!"); } Lecture03

1.Prompting the User for Input Example 2 Reading a floating point number from the keyboard: How old are you? 65 65... That's quite old! import java.util.Scanner; ... Scanner console = new Scanner(System.in); double x = console.nextDouble(); Lecture03

age / value + (number - age) 2.Expressions An expression is code that can be evaluated to give a single value: Combination of variables, constants, operators, and parentheses Examples of expressions Arithmetic Expressions Relational Expressions Logical Expressions 35 age 3 * number + 56 age / value + (number - age) Lecture03

3. Arithmetic Expressions The Arithmetic Operators Combine variables and constants with arithmetic operators and parentheses Note: The arithmetic operators are binary operators because they each operate on two operands. Integer division yields an integer quotient. Any fractional part in integer division is simply truncated (i.e., discarded)—no rounding occurs. The remainder operator, %, yields the remainder after division. Operator Description + Additive operator (also used for String concatenation) - Subtraction operator * Multiplication operator / Division operator % Modulus / Remainder operator 10 / 4 Result is 2 Lecture03

3. Arithmetic Expressions Mixing Types When a Java operator is applied to operands of different types, Java does a widening conversion automatically, known as a promotion. Conversions are done on one operator at a time in the order the operators are evaluated. 2.2 * 2 evaluates to 4.4 1.0 / 2 evaluates to 0.5 double x = 2; assigns 2.0 to x 5.0 7.16666 3 / 2 * 3.0 + 8 / 3 2.0 * 4 / 5 + 6 / 4.0 3.1 Lecture03

3.Arithmetic Expressions The Unary Operators Example: Operator Description + Unary plus operator; indicates positive value (numbers are positive without this, however) - Unary minus operator; negates an expression ++ Increment operator; increments a value by 1 -- Decrement operator; decrements a value by 1 ! Logical complement operator; inverts the value of a boolean int a = 0; a++; System.out.println(a); int b = 4; b--; System.out.println(b); 1 3 Lecture03

3.Arithmetic Expressions Post-increment Vs Pre-increment Post Increment : i++ Increment Value of Variable After Assigning Pre Increment : ++i First Increment Value and then Assign Value. Post-decrement: i--, Pre-decrement: --i int i = 0, j = -1; j = i++; System.out.println(j); int p = 0, q = -1; q = ++p; System.out.println(q); 1 Lecture03

Exercise 1 What is the output of the following program? public class L03Ex01{ public static void main(String[] args) { int num1=100, num2=1, num3; num3 = num2++ + ++num1; System.out.print(" num1=" + num1); System.out.print(" num2=" + num2); System.out.print(" num3=" + num3); } Lecture03

3.Arithmetic Expressions The Assignment Operators Example: Operator Description += Add AND assignment operator C += A is equivalent to C = C + A -= Subtract AND assignment operator C -= A is equivalent to C = C - A *= Multiply AND assignment operator  C *= A is equivalent to C = C * A /= Divide AND assignment operator C /= A is equivalent to C = C / A %= Modulus AND assignment operator C %= A is equivalent to C = C % A int x = 1; x += 2; System.out.println(x); int y = 8; y /= 2; System.out.println(y); 3 4 Lecture03

3.Arithmetic Expressions Multiple assignments Embed assignment expressions within assignment expressions Example: s = 5 + (t = 4) Evaluates to 9 while t is assigned 4 int s = 1, t = 2; s = 5 + (t = 4); System.out.println(s); System.out.println(t); 9 4 Lecture03

3.Arithmetic Expressions The + operator The + operator can be used in two ways. as a concatenation operator as an addition operator If either side of the + operator is a string, the result will be a string. Example: int value = 5; System.out.println("Hello " + "World"); System.out.println("The value is: " + 5); System.out.println("The value is: " + value); System.out.println("The value is: " + '\n' + 5); Hello World The value is: 5 The value is: 5 Lecture03

3.Arithmetic Expressions Order of precedence The evaluation of expressions follows these two rules: highest precedence operators are always evaluated first if operators have the same precedence, then evaluation is from left to right Lecture03

4.Relational Expressions Combine variables and constants with relational, or comparison, and equality operators and parentheses Relational or comparison operators: <, <=, >=. > Equality operators: ==, != Evaluate to true or false Note: Common programming Error Confusing the equality operator ‘==‘ with the assignment operator ‘=‘ int value = 5; System.out.println(value > 5); false int value = 5; System.out.println(a=5); System.out.println(a==5); 5 true Lecture03

Exercise 2 & 3 What is the output of the following program? int a, b; double c; System.out.println(7 + 1 + "4 * 2" + 3 + 1); System.out.println("5" + (7 + 1) + 3 * 2 + 1); a = 5; b = a / 3 + 1; c = a / b; System.out.println(a + ", " + b + ", " + c); int val1 = 50; int val2 = 53; System.out.println("1. " + (val1 != val2)); System.out.println("2. " + (val1 >= val2 - 3)); System.out.println("3. " + (67 % 2 == 1)); Lecture03

5.Logical Expressions Logical expressions Combine variables and constants of arithmetic types, relational expressions with logical operators Logical And: && Logical Or: || Logical unary NOT: ! Evaluate to true or false Note: Comparison operators can be chained 1 < value < 100 value > 1 && value < 100 value >= 1 || value == 5 Lecture03

5.Logical Expressions Order of precedence Logical operators in the order of precedence Example: expression a && !b || c would be evaluated as (a && (!b)) || c Parentheses can be used to change the order of evaluation Example: a && (!b || c) Operator Meaning Example high ! Not ! ( a == b) && And (a == b) && (c ==d) low || Or (a == b) || (c ==d) Lecture03

5.Logical Expressions More Examples is the value greater than 10 and less than 100 value > 10 && value < 100 is the value greater than 10 or is the value equal to 1 value > 10 || value == 1 is the value not greater than 10 !(value > 10) (value <= 10) is the value not greater 10 and not equal to 1 either value <= 10 && value != 1 or !(value > 10 || value == 1) Lecture03

5.Logical Expressions Short-circuit evaluation Meaning Short circuit? && and yes & no || or | Short-circuit evaluation Stops as soon as the value of expression is determined Truth table: The OR operator results in true when A is true, no matter what B is. Similarly, the AND operator results in false when A is false, no matter what B is. A B And Operator Or operator T F true Skip the second part as the result is always TRUE true System.out.println(a>0 || value>a/0); Must evaluate the second part -> generate an error false System.out.println(a>10 || value>a/0); Exception in thread "main" java.lang.ArithmeticException: / by zero Lecture03

5.Logical Expressions Common Errors Mathematics shortcuts do not work in Java. Not valid in Java if (10 < b < 20) { doSomething(); } if (10 < b && b < 20) { Remember that the equality test uses double equals == Tries to do assignment if (a = b) { doSomething(); } if (a == b) { Lecture03

Summary Operator Precedence Operations with higher order of precedence are applied first ! Operation Symbol high Grouping operators ( ) Higher order of precedence Unary operators +, -, ! Multiplicative arithmetic *, /, % Additive arithmetic +, - Relational ordering <, >, <=, >= Relational equality ==, != Logical and && Logical or || low Assignment =, +=, -=, *=, /=, %= Lecture03

! Exercise 4 What is the output of the following program? public class L03Ex04 { public static void main(String[] args) { int value = 12; boolean result; result = value>10 || value<=5 && value!=12; System.out.println("1. " + result); result = (value>10 || value<=5) && value!=12; System.out.println("2. " + result); } ! High Precedence! Lecture03

Exercise 5 Write a program that averages the rain fall for three months, April, May, and June. Declare and initialize a variable to the rain fall for each month. Compute the average, and write out the results, something like: Rainfall for April: 12 Rainfall for May : 14 Rainfall for June: 8 Average rainfall: 11.33 //import public class L03Ex05 { public static void main(String[] args) { int april, may, june; double average; //create a scanner object //get rainfall x 3 times //calculate the average average = (april + may + june)/3; System.out.printf("Average rainfall: %.2f%n", average); } What is wrong here? Rainfall for April: 12 Rainfall for May : 14 Rainfall for June: 8 Average rainfall: 11.00 ! Lecture03