John Hurley Cal State LA CS 201 Lecture 4. If If statements do just what you expect test whether a condition is true and if so, execute some statements.

Slides:



Advertisements
Similar presentations
Fundamental Programming Structures in Java: Control Flow, Arrays and Vectors.
Advertisements

L5:CSC © Dr. Basheer M. Nasef Lecture #5 By Dr. Basheer M. Nasef.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4: Selections.
Control Structures Corresponds with Chapters 3 and 4.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 3 Control Statements.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Introduction to Java Programming, 4E Y. Daniel Liang.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 3 Control Statements.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.1 Chapter 3 Selections.
C++ for Engineers and Scientists Third Edition
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Control Statements.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
UNIT II Decision Making And Branching Decision Making And Looping
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
INF120 Basics in JAVA Programming AUBG, COS dept Lecture 05 Title: Decision/Selection Control Structures Reference: MalikFarrell, chap 1, Liang Ch 3.
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.1 Chapter 3 Selections.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Chapter 3 Selections Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Information  HW1 now available  Group Project (Find your group members)  Start thinking about group projects.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Introduction to Control Statements JavaScript – Part 3 George Mason University June 3, 2010.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. CHAPTER 3: SELECTIONS 1.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Lecture 3 Decisions (Conditionals). One of the essential features of computer programs is their ability to make decisions. Like a train that changes tracks.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.1 Chapter 3 Selections.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
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.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall Java Programming.
1 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.1 Chapter 3 Selections.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
1 Chapter 5 Control Statements. 2 Objectives F To understand the flow of control in selection and loop statements. F To use Boolean expressions to control.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.1 Chapter 3 Selections.
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.
Chapter 7 Control Structures. Java has very flexible three looping mechanisms. You can use one of the following three loops:  while Loop  do...while.
John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:
Introduction to Control Statements IT108 George Mason University.
John Hurley Spring 2011 Cal State LA CS 201 Lecture 5:
Lecture 4: Introduction to Control Flow Statements and Reading User Input Michael Hsu CSULA.
Chapter 3 Selections Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved
Lecture 3 Selection Statements
Group Project (Find your group members)
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
INTERMEDIATE PROGRAMMING USING JAVA
Chapter 3 Control Statements
CS0007: Introduction to Computer Programming
CS 201 Lecture 7: John Hurley Summer 2012 Cal State LA.
Selections Java.
Lecture 3- Decision Structures
Chapter 3 Selections ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH Introduction to Java Programming, Liang (Pearson 2014)
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Chapter 5 Control Statements
Chapter 3 Selections Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1.
Chapter 3 Selections Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Chapter 3 Control Statements
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
Lecture Notes – Week 2 Lecture-2
Conditionals.
Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Chapter 3 Selections Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1.
Presentation transcript:

John Hurley Cal State LA CS 201 Lecture 4

If If statements do just what you expect test whether a condition is true and if so, execute some statements syntax: if(test) { // statements to execute is condition is true } Example: if(x < y){ System.out.println(“x < y”); }

If

If there is only one statement in the block, you can omit the brackets: if(x < y) System.out.println(“x < y”); Note that there is no semicolon between the condition and the statements to execute!

If public class IfDemo{ public static void main(String[] args){ int firstInt = 0; int secondInt = 1; if(firstInt < secondInt) System.out.println(firstInt + " < " + secondInt); if(firstInt == secondInt) System.out.println(firstInt + " = " + secondInt); if(firstInt > secondInt) System.out.println(firstInt + " > " + secondInt); }

If / else If can be followed by else: if(condition) { // statements to execute if condition is true } else { // statements to execute if condition is false }

If / elseif / else We can also use else if, with or without a final else: if(condition 1) { // statements to execute if condition 1 is true } else if(condition 2) { // statements to execute if condition 1 is false but condition 2 is true } // can use any number of else if blocks else { // statements to execute if condition none of the conditions are true }

8 Multiple Alternative if Statements

If / elseif / else public class IfElseDemo{ public static void main(String[] args){ int firstInt = 5; for(int secondInt = 0; secondInt < 10; secondInt++){ char compare; if(firstInt < secondInt) compare = '<'; else if(firstInt > secondInt) compare = '>'; else compare = '='; System.out.println(firstInt + " " + compare + " " + secondInt); } // end for } // end main() } // end class

If / else shorthand Syntax: condition?value if condition is true:value if condition is false; System.out.println(a<b?"true!":"false!"); This is equivalent to the following: if(a < b) System.out.println(“true”); else System.out.prinltn(“false”);

If / else shorthand public class ShorthandDemo{ public static void main(String[] args){ int firstInt = 5; for(int secondInt = 0; secondInt < 10; secondInt++){ String comp = null; int a = 0; a=(firstInt < secondInt)?1:0; System.out.println(a); System.out.println(firstInt < secondInt?"true!":"false!"); } // end for } // end main() } // end class

Logical Operators AND: && if(condition 1 && condition 2) {} example: if(a < b && b < 1) c = 1; example 2: if(a < b && a < 0) System.out.println(“a is negative and less than b”); OR: || if(condition 1 || condition 2) {} example: if(a < b || b < 1) c = 1; NOT: ! !(a == b) is equivalent to (a != b) Can also use with more complex conditions !((a == b) && (a == 1)) !(a || b) !(a &&(b||c)) Can string any number of conditions together, but be careful not to write code that is hard to understand

Multiple Conditions public class MultipleConditionsDemo{ public static void main(String[] args){ boolean trueCondition = true; boolean falseCondition = false; System.out.println("True is " + (trueCondition?"true":"false")); System.out.println("False is " + (falseCondition?"true":"false")); System.out.println("(True and False) is "+(trueCondition&& falseCondition?"true":"false")); System.out.println("(True or False) is "+(trueCondition||falseCondition?"true":"false")); } // end main() } // end class

Negations

public class BangDemo{ public static void main(String[] args){ boolean a = true; boolean b = true; boolean c = true; System.out.println(!(a &&(b||c))); c = false; System.out.println(!(a &&(b||c))); b = false; c = true; System.out.println(!(a &&(b||c))); b = false; c = false; System.out.println(!(a &&(b||c)));

Negations a = false; b = true; c = true; System.out.println(!(a &&(b||c))); c = false; System.out.println(!(a &&(b||c))); b = false; c = true; System.out.println(!(a &&(b||c))); b = false; c = false; System.out.println(!(a &&(b||c))); } // end main() } // end class

Nested If Blocks One if block can be inside another one The inner if only runs if the condition in the outer one evaluates to true Can be nested to any depth, but this quickly gets confusing We will soon see nested loops, too!

Nested If Blocks if(condition 1) { // statements execute if condition 1 is true if (condition 2){ // statements execute if condition 1 and condition 2 are both true } else { // statements execute if condition 1 is true but condition 2 is false } else{ // statements execute if condition 1 is false }

Nested If Blocks public class NestedIfDemo{ public static void main(String[] args){ boolean trueCondition = true; boolean falseCondition = false; if(trueCondition){ if(falseCondition) System.out.println("true and false"); else System.out.println("true and ~false"); } else{ if(falseCondition) System.out.println("~true and false"); else System.out.println("~true and ~false"); } } // end main() } // end class

Equality with Floating Point Types Due to the limited precision of floating point types, it is unwise to test floats and doubles with == operator: public static void main(String[] args) { double d = ; double e = d; e = e + 1; e = e - 1; System.out.println("d = " + d + "; e = " + e); } // end main()

Equality with Floating Point Types Instead of using equality test, use Math.abs as follows: Math.abs(a-b) < tolerance; For example, if(Math.abs(grade - 3.7) <.02) {}

Switch Chooses one statement or block to execute from among several options, based on the value of a variable switch (status) { case 0: compute taxes for single filers; break; case 1: compute taxes for married file jointly; break; case 2: compute taxes for married file separately; break; case 3: compute taxes for head of household; break; default: System.out.println("Errors: invalid status"); System.exit(0); }

23 switch Statement Flow Chart

24 switch Statement Rules switch (switch-expression) { case value1: statement(s)1; break; case value2: statement(s)2; break; … case valueN: statement(s)N; break; default: statement(s)-for- default; } The switch-expression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses. The value1,..., and valueN must have the same data type as the value of the switch- expression. The resulting statements in the case statement are executed when the value in the case statement matches the value of the switch-expression. Note that value1,..., and valueN are constant expressions, meaning that they cannot contain variables in the expression, such as 1 + x.

25 switch Statement Rules The keyword break is optional, but it should be used at the end of each case in order to terminate the remainder of the switch statement. If the break statement is not present, the next case statement will be executed. switch (switch-expression) { case value1: statement(s)1; break; case value2: statement(s)2; break; … case valueN: statement(s)N; break; default: statement(s)-for- default; } The default case, which is optional, can be used to perform actions when none of the specified cases matches the switch-expression. The case statements are executed in sequential order, but the order of the cases (including the default case) does not matter. However, it is good programming style to follow the logical sequence of the cases and place the default case at the end.

26 Trace switch statement switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch); } Suppose ch is 'a': animation

27 Trace switch statement switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch); } ch is 'a': animation

28 Trace switch statement switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch); } Execute this line animation

29 Trace switch statement switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch); } Execute this line animation

30 Trace switch statement switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch); } Execute this line animation

31 Trace switch statement switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch); } Next statement; Execute next statement animation

32 Trace switch statement switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break ; case 'c': System.out.println(ch); } Suppose ch is 'a': animation

33 Trace switch statement switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break ; case 'c': System.out.println(ch); } ch is 'a': animation

34 Trace switch statement switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break ; case 'c': System.out.println(ch); } Execute this line animation

35 Trace switch statement switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break ; case 'c': System.out.println(ch); } Execute this line animation

36 Trace switch statement switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break ; case 'c': System.out.println(ch); } Next statement; Execute next statement animation

Command Line Input There are several ways to get input from a command line In production, you will usually write programs that use GUIs, not command line I/O In school most programming classes focus on functionality, not user interface, so you need to know how to use command line I/O

Command Line Input The simplest command line input class is Scanner import java.util.Scanner; Scanner has a variety of methods to get input of different data types

Scanner Input Methods We describe methods using in this format: Class.method() If there are any parameters, their type goes inside the parentheses You have already seen System.out.println(String) You will often replace the class name with the name of an instance of the class: Scanner input = new Scanner(System.in); … stuff deleted… name = input.next(); In the example above, input is an instance of Scanner. We set up a Scanner and called it input!

Scanner Input Methods Scanner.next() reads the next parsable String Scanner.nextLine() reads up to the next line break and puts the result in a String Scanner.nextDouble() reads the next parseable string and tries to convert it to a Double double d = Scanner.nextDouble(); There are equivalent methods for nextInteger(), nextBoolean(), etc.

Scanner.next Example package demos; import java.util.Scanner; public class InputDemo { public static void main(String[] args) { Scanner input = new Scanner(System.in); String name = null; System.out.println("Guess my name:"); name = input.next(); if (name.equals("Rumpelstiltskin")) System.out.println("Correct! Continue spinning straw into gold!"); else System.out.println("Wrong! I will now eat your children!"); }

Scanner.nextDouble Example import java.util.Scanner; public class ReadDouble { public static void main(String[] args) { Scanner input = new Scanner(System.in); double myDouble = 0.0; do { System.out.print("Input a double:"); myDouble = input.nextDouble(); System.out.println("\nYou entered: " + myDouble); } while (stuff != 0.0); }

Switch public static void main(String[] args) { Scanner sc = new Scanner(System.in); char ageCat = 'y'; while (ageCat != 'q') { System.out.println("Welcome to John's bar. Please enter your age category: \ny for under 21, m for 21-29, o for 30 and older. Enter q to quit."); String input = sc.next(); ageCat = (char) input.charAt(0); switch (ageCat) { case 'y': System.out.println("Enjoy your Shirley Temple, Junior"); break; case 'm': System.out.println("You'd better stick to beer"); break; case 'o': System.out.println("There's whiskey in the jar."); break; case 'q': break; default: System.out.println("Invalid input"); } // end switch } // end while } // end main()

Eclipse IDE 44 IDE = Integrated Development Environment An IDE provides services that make it easier for you to program Editor with syntax checking, automatic formatting, etc One-step compile and run Debugging Organization

Eclipse IDE 45 The IDE most often used for Java programming is called Eclipse. Eclipse is the standard IDE at CSULA. Eclipse supports many different programming languages with available plug-ins, but it is mostly used for Java Eclipse is open-source; you can get it at Get the “Eclipse IDE for Java Developers” Others often used with Java include NetBeans, JBuilder, many others

Eclipse IDE 46 IDE = Integrated Development Environment An IDE provides services that make it easier for you to program Editor with syntax checking, automatic formatting, etc One-step compile and run Debugging Organization

Eclipse IDE 47 The most widely used IDE at CSULA is Eclipse. Eclipse supports many different programming languages with available plug-ins, but it is mostly used for Java Eclipse is open-source; you can get it at Get the “Eclipse IDE for Java Developers” Others often used with Java include NetBeans, JBuilder, many others

Eclipse IDE 48 The current general-release version of Eclipse predates the most recent update to the JDK. If you don’t already have Eclipse working on your home computer, you may deal with this in one of two ways: Get the JDK 7 instead of 8, OR Get the JDK 8 and then follow the easy instructions at

Eclipse IDE 49 Create a new project in Eclipse and write a class

Eclipse: Create a Project

Add a Code Package

Add a class

Write code in the class

Run the project At least one class must have a main()!

“Run Configurations” is critical

“Window/Preferences” contains many settings