The if-else statement. Introducing the if-else statement Programming problem: Re-write the a,b,c-formula program to solve for complex number solutions.

Slides:



Advertisements
Similar presentations
Numeric literals and named constants. Numeric literals Numeric literal: Example: A numeric literal is a constant value that appears in a Java program.
Advertisements

1 Control Structures (and user input). 2 Flow of Control The order statements are executed is called flow of control By default, statements in a method.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
Nested conditional statements. Previously discussed Conditional statements discussed so far: Syntax of the if-statement: if-statement if-else-statement.
The switch statement: an N-way selection statement.
Writing algorithms using the while-statement. Previously discussed Syntax of while-statement:
Writing algorithms using the for-statement. Programming example 1: find all divisors of a number We have seen a program using a while-statement to solve.
Programming a computer. What does programming a computer mean ? Programming a computer: Since a computer can only execute machine instructions (encoded.
The break and continue statements. Introduction There are 2 special statements that can affect the execution of loop statements (such as a while-statement)
Week 2 - Friday.  What did we talk about last time?  Data representation  Binary numbers  Types  int  boolean  double  char  String.
Shorthand operators.
CSC 1051 M.A. Papalaskari, Villanova University Repetition CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing.
The character data type char
Chapter 6 Iteration.  Executes a block of code repeatedly  A condition controls how often the loop is executed while (condition) statement  Most commonly,
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
The string data type String. String (in general) A string is a sequence of characters enclosed between the double quotes "..." Example: Each character.
The Rectangle Method. Introduction Definite integral (High School material): A definite integral a ∫ b f(x) dx is the integral of a function f(x) with.
Lecture 2: Classes and Objects, using Scanner and String.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
The dangling-else ambiguity. Previously discussed The Java compiler (translator) consider white space characters (i.e., SPACE, TAB and New line) as insignificant.
The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
1 Debugging. 2 A Lot of Time is Spent Debugging Programs Debugging. Cyclic process of editing, compiling, and fixing errors. n Always a logical explanation.
Floating point numerical information. Previously discussed Recall that: A byte is a memory cell consisting of 8 switches and can store a binary number.
The scope of local variables. Murphy's Law The famous Murphy's Law says: Anything that can possibly go wrong, does. (Wikipedia page on Murphy's Law:
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Boolean expressions, part 2: Logical operators. Previously discussed Recall that there are 2 types of operators that return a boolean result (true or.
CSI 1390: Introduction to Computers TA: Tapu Kumar Ghose Office: STE 5014 Office hours: Thursday 1300 – 1400hrs.
Lecture 3 Decisions (Conditionals). One of the essential features of computer programs is their ability to make decisions. Like a train that changes tracks.
Working with arrays (we will use an array of double as example)
Introduction to programming in the Java programming language.
Assignment statements using the same variable in LHS and RHS.
First Programs CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
The if-else statement. The if-else statement in Java The if-else statement is the second conditional statement in Java The if-else statement selects one.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
Mixing integer and floating point numbers in an arithmetic operation.
Introduction to Methods. Previously discussed There are similarities in make up of that can help you remember the construct of a class a class in the.
The Bisection Method. Introduction Bisection Method: Bisection Method = a numerical method in Mathematics to find a root of a given function.
Integer numerical data types. The integer data types (multiple !) The integer data types use the binary number system as encoding method There are a number.
Using the while-statement to process data files. General procedure to access a data file General procedure in computer programming to read data from a.
The while-statement. Syntax and meaning of the while-statement The LOOP-CONTINUATION-CONDITION is a Boolean expression (exactly the same as in the condition.
The assignment expressions. The assignment operator in an assignment statement We have seen the assignment statement: Effect: var = expr; Stores the value.
The while-statement. The loop statements in Java What is a loop-statement: A loop-statement is a statement that repeatedly executes statements contained.
Arithmetic expressions containing Mathematical functions.
Reading input from the console input. Java's console input The console is the terminal window that is running the Java program I.e., that's the terminal.
Introduction to array: why use arrays ?. Motivational example Problem: Write a program that reads in and stores away 5 double numbers After reading in.
Working with floating point expressions. Arithmetic expressions Using the arithmetic operators: and brackets (... ), we can construct arithmetic expression.
Boolean expressions, part 1: Compare operators. Compare operators Compare operators compare 2 numerical values and return a Boolean (logical) value A.
Simple algorithms on an array - compute sum and min.
The ++ and -- expressions. The ++ and -- operators You guessed it: The ++ and -- are operators that return a value.
import java.util.Scanner; class myCode { public static void main(String[] args) { Scanner input= new Scanner(System.in); int num1; System.out.println(“Enter.
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.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Variable scope. Variable Scope Variables do not live forever. Failing to take that into account leads to problems. Let's look at an example. Let's write.
Chapter 7 Iteration. Chapter Goals To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To.
Chapter 2 Elementary Programming
Chapter 3 Selections ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH Introduction to Java Programming, Liang (Pearson 2014)
Repetition-Counter control Loop
TK1114 Computer Programming
SELECTION STATEMENTS (1)
First Programs CSE 1310 – Introduction to Computers and Programming
The Boolean (logical) data type boolean
Building Java Programs
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
CSC 1051 – Data Structures and Algorithms I
The for-statement.
Presentation transcript:

The if-else statement

Introducing the if-else statement Programming problem: Re-write the a,b,c-formula program to solve for complex number solutions when b 2 - 4ac < 0

Introducing the if-else statement (cont.) Algorithm: input a, b, c; Det = b*b - 4*a*c; // Compute the determinant if ( Det >= 0 ) { print -b/(2a) + sqrt(Det)/(2a); // Real number solutions print -b/(2a) - sqrt(Det)/(2a); } if ( Det < 0 ) { print -b/(2a) "+" (sqrt(-Det)/(2a) + "i"); // Complex number solutions print -b/(2a) "-" (sqrt(-Det)/(2a) + "i"); }

Introducing the if-else statement (cont.) Java program: import java.util.Scanner; public class Abc3 { public static void main(String[] args) { double a, b, c, Det, re, im; Scanner in = new Scanner(System.in); // Construct Scanner object a = in.nextDouble(); // Read in next number into a b = in.nextDouble(); // Read in next number into b c = in.nextDouble(); // Read in next number into c

Introducing the if-else statement (cont.) Det = b*b - 4*a*c; if ( Det >= 0 ) { System.out.println( (-b + Math.sqrt( Det ) ) / (2*a) ); System.out.println( (-b - Math.sqrt( Det ) ) / (2*a) ); } if ( Det < 0 ) { re = -b/(2*a); // Compute real part im = Math.sqrt( -Det )/(2*a); // Compute imaginary part System.out.println( re + "+" + im + "i" ); System.out.println( re + "-" + im + "i" ); }

Introducing the if-else statement (cont.) Example Program: (Demo above code) –Prog file: Abc3.java How to run the program: Right click on link and save in a scratch directory To compile: javac Abc3.java To run: java Abc3

Introducing the if-else statement (cont.) Example: Enter a:1 Enter b:2 Enter c: i i

Introducing the if-else statement (cont.) Shortcoming: We have to negate the if-condition ourselves... This can introduce unnecessary errors

Introducing the if-else statement (cont.) Solution: Extend the if-statement with an alternative statement The alternative statement is only executed when the if-condition is false

The if-else statement in Java The if-else statement: The if-else statement is the second conditional statement in Java The if-else statement selects one of two statements to be executed based on a given condition

Syntax and meaning of the if-else-statement Syntax of the if-else-statement: if ( CONDITION ) ONE- statement else ONE-statement

Syntax and meaning of the if-else-statement (cont.) Explanation: The keyword if announces (to the Java compiler) that we started an if-else-statement A conditional clause ( CONDITION ) follows the keyword if This is the condition of the if-else-statement

Syntax and meaning of the if-else-statement (cont.) This is the condition of the if-else-statement Following the condition clause, you can write (only) one statement Following the then-part, you must specify the keyword else followed by (only) one statement This statement will only be executed if the condition is true This statement will only be executed if the condition is false

Syntax and meaning of the if-else-statement (cont.) Note: The way that the Java compiler decide whether a conditional statement is: is by the presence/absence of the keyword else. An if-statement An if-else-statement

Computer Jargon: else-part The statement following the keyword else in an if-else- statement is called The else-part of the if-else-statement (Or else-part for short)

Computer Jargon: else-part (cont.) Schematically:

The a,b,c-formula using an if-else-statement Programming problem: Algorithm: Re-write the a,b,c-formula program to solve for complex number solutions when b 2 - 4ac < 0

The a,b,c-formula using an if-else-statement (cont.) Java program: import java.util.Scanner; public class Abc4 { public static void main(String[] args) { double a, b, c, Det, re, im; Scanner in = new Scanner(System.in); // Construct Scanner object a = in.nextDouble(); // Read in next number into a b = in.nextDouble(); // Read in next number into b c = in.nextDouble(); // Read in next number into c Det = b*b - 4*a*c;

The a,b,c-formula using an if-else-statement (cont.) if ( Det >= 0 ) { System.out.println( (-b + Math.sqrt( Det ) ) / (2*a) ); System.out.println( (-b - Math.sqrt( Det ) ) / (2*a) ); } else { re = -b/(2*a); // Compute real part im = Math.sqrt( -Det )/(2*a); // Compute imaginary part System.out.println( re + "+" + im + "i" ); System.out.println( re + "-" + im + "i" ); }

The a,b,c-formula using an if-else-statement (cont.) Example Program: (Demo above code) –Prog file: Abc4.java How to run the program: Right click on link and save in a scratch directory To compile: javac Abc4.java To run: java Abc4

Programming example: find maximum of 2 numbers Programming problem: Read in 2 number a and b Assign to the variable max the largest value of a and b

Programming example: find maximum of 2 numbers (cont.) Algorithm:

Programming example: find maximum of 2 numbers (cont.) Java program: import java.util.Scanner; public class Max01 { public static void main(String[] args) { double a, b, max; Scanner in = new Scanner(System.in); // Construct Scanner object a = in.nextDouble(); // Read in next number into a b = in.nextDouble(); // Read in next number into b if ( a >= b ) max = a; else max = b; System.out.println( "max value = " + max ); }

Programming example: find maximum of 2 numbers (cont.) Example Program: (Demo above code) –Prog file: Max01.java How to run the program: Right click on link and save in a scratch directory To compile: javac Max01.java To run: java Max01

Program example: find maximum of 3 numbers Programming problem: Read in 3 number a, b and c Assign to the variable max the largest value of a, b and c

Program example: find maximum of 3 numbers (cont.) Algorithm:

Program example: find maximum of 3 numbers (cont.) Java program: import java.util.Scanner; public class Max01 { public static void main(String[] args) { double a, b, max; Scanner in = new Scanner(System.in); // Construct Scanner object a = in.nextDouble(); // Read in next number into a b = in.nextDouble(); // Read in next number into b c = in.nextDouble(); // Read in next number into c

Program example: find maximum of 3 numbers (cont.) if ( a >= b ) // Find max(a,b) max = a; else max = b; if ( c > max ) // Check c > max ? max = c; System.out.println( "max value = " + max ); }

Program example: find maximum of 3 numbers (cont.) Example Program: (Demo above code) –Prog file: Max02.java How to run the program: Right click on link and save in a scratch directory To compile: javac Max02.java To run: java Max02

Programming example: leap year Leap year description (Wikipedia): In the Gregorian calendar, the current standard calendar in most of the world, most years that are evenly divisible by 4 are leap years. Years that are evenly divisible by 100 are not leap years, unless they are also evenly divisible by 400, in which case they are leap years

Programming example: leap year (cont.) Algorithm:

Programming example: leap year (cont.) Program in Java: import java.util.Scanner; public class LeapYear01 { public static void main(String[] args) { int year; boolean leap;

Programming example: leap year (cont.) Scanner in = new Scanner(System.in); // Construct Scanner object year = in.nextInt(); // Read in year if ( year % 4 == 0 ) leap = true; else leap = false; if ( year % 100 == 0 ) leap = false; if ( year % 400 == 0 ) leap = true; System.out.println("Year is leap year ? " + leap); }

Programming example: leap year (cont.) Example Program: (Demo above code) –Prog file: LeapYear01.java How to run the program: Right click on link and save in a scratch directory To compile: javac LeapYear01.java To run: java LeapYear01

Common errors in if-else-statements Common error 1: bogus semicolon after the if-condition Example: if ( a >= b ) ; // Bogus ; max = a; else max = b;

Common errors in if-else-statements (cont.) Compiler message: Error01.java:18: 'else' without 'if' else ^

Common errors in if-else-statements (cont.) because the compiler "reads" the program as follows: if ( a >= b ) // A correct if-statement ; // Note: the if-statement ended here ! max = a; // A correct assignment statement else // else ? Where is the if ??? max = b;

Common errors in if-else-statements (cont.) Common error 2: forgetting to use statement block in the then-part Example: if ( Det >= 0 ) System.out.println( (-b + Math.sqrt( Det ) ) / (2*a) ); System.out.println( (-b - Math.sqrt( Det ) ) / (2*a) ); else re = -b/(2*a); // Compute real part im = Math.sqrt( -Det )/(2*a); // Compute imaginary part System.out.println( re + "+" + im + "i" ); System.out.println( re + "-" + im + "i" );

Common errors in if-else-statements (cont.) The Java compiler will report the error 'else' without 'if' because syntactically, the program is read as follows: if ( Det >= 0 ) System.out.println( (-b + Math.sqrt( Det ) ) / (2*a) ); // If-statement System.out.println( (-b - Math.sqrt( Det ) ) / (2*a) ); // Print else // Else without if re = -b/(2*a); // Compute real part im = Math.sqrt( -Det )/(2*a); // Compute imaginary part System.out.println( re + "+" + im + "i" ); System.out.println( re + "-" + im + "i" );

Common errors in if-else-statements (cont.) Common error 3: missing semicolon after the then-part Example: if ( a >= b ) max = a // Missing semicolon !!! else max = b;

Common errors in if-else-statements (cont.) Compiler message: Error03.java:17: ';' expected max = a ^

Common errors in if-else-statements (cont.) Reason: The then-part is ONE statement A statement must be ended with a semicolon

Common errors in if-else-statements (cont.) Common error 4: bogus semicolon after the block in the then-part Example: if ( a >= b ) { max = a; }; // bogus semicolon !!! else { max = b; }

Common errors in if-else-statements (cont.) Compiler message: Error04.java:20: 'else' without 'if' else ^

Common errors in if-else-statements (cont.) Reason: The then-part is ONE statement A statement must be ended with a semicolon

Common errors in if-else-statements (cont.) Common error 4: bogus semicolon after the block in the then-part Example: if ( a >= b ) { max = a; }; // bogus semicolon !!! else { max = b; }

Common errors in if-else-statements (cont.) Compiler message: Error04.java:20: 'else' without 'if' else ^

Common errors in if-else-statements (cont.) Because syntactically, the program is read as follows: if ( a >= b ) // An if-statement { max = a; } ; // An empty statement !!! else // Else without if... { max = b; }

Programming advice As you can see, forgetting a ";" and adding an extra ";" can cause serious syntax errors The best thing is to stick to one useful form: use block !!!

Programming advice (cont.) I always write if-statements and if-else-statements using blocks first: if (..... ) { (leave empty first) } if (..... ) { (leave empty first) } else { (leave empty first) }

Programming advice (cont.) I fill in the statements in the then-part and else-part later. So even when the if-part and/or else-part consist of 1 statement, I write them as blocks.