john hurley cal state la cs 201 lecture 4. if if statements do just what you expect test whether a...

58
John Hurley Cal State LA CS 201 Lecture 4

Upload: augustus-mcdonald

Post on 16-Jan-2016

220 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 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

John HurleyCal State LA

CS 201 Lecture 4

Page 2: 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

If

If statements do just what you expecttest whether a condition is true and if so, execute

some statementssyntax:if(test) {

// statements to execute is condition is true}

Example: if(x < y){

System.out.println(“x < y”);}

Page 3: 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

If

Boolean Expression

false true

Statement(s) for the false case Statement(s) for the true case

Page 4: 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

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!

Page 5: 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

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

}

Page 6: 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

If / elseIf can be followed by else:

if(condition) {// statements to execute if

condition is true}

else {// statements to execute if

condition is false}

Page 7: 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

If / elseif / elseWe 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}

Page 8: 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

8

Multiple Alternative if Statements

if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F';

Equivalent

if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F';

Page 9: 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

If / elseif / elsepublic 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

Page 10: 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

If / else shorthandSyntax:

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

Page 11: 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

If / else shorthandpublic 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

Page 12: 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

Logical OperatorsAND: &&

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

Page 13: 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

Multiple Conditionspublic 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

Page 14: 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

Negations

a b c b||c a &&(b||c) !(a &&(b||c))T T T T T FT T F T T FT F T T T FT F F F F TF T T T F TF T F T F TF F T T F TF F F F F T

Page 15: 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

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

Page 16: 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

Negationsa = 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

Page 17: 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

Nested If Blocks

One if block can be inside another oneThe inner if only runs if the condition in the

outer one evaluates to trueCan be nested to any depth, but this quickly

gets confusingWe will soon see nested loops, too!

Page 18: 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

Nested If Blocksif(condition 1) {

// statements execute if condition 1 is trueif (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

}

Page 19: 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

Nested If Blockspublic 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

Page 20: 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

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 = 1.23456789;double e = d;e = e + 1;e = e - 1;System.out.println("d = " + d + "; e = " + e);

} // end main()

Page 21: 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

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

Page 22: 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

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

Page 23: 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

23

switch Statement Flow Chart

status is 0 Compute tax for single filers break

Compute tax for married file jointly break status is 1

Compute tax for married file separatly break status is 2

Compute tax for head of household break status is 3

Default actions default

Next Statement

Page 24: 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

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.

Page 25: 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

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.

Page 26: 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

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

Page 27: 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

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

Page 28: 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

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

Page 29: 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

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

Page 30: 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

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

Page 31: 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

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

Page 32: 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

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

Page 33: 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

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

Page 34: 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

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

Page 35: 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

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

Page 36: 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

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

Page 37: 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

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

Page 38: 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

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

Page 39: 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

Scanner Input MethodsWe describe methods using in this format:

Class.method()If there are any parameters, their type goes inside

the parenthesesYou 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!

Page 40: 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

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.

Page 41: 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

Scanner.next Examplepackage 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!");

elseSystem.out.println("Wrong! I will now eat your

children!");}

}

Page 42: 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

Scanner.nextDouble Exampleimport 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);

}}

Page 43: 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

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

Page 44: 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

Eclipse IDE

44

IDE = Integrated Development EnvironmentAn IDE provides services that make it easier for you to program

Editor with syntax checking, automatic formatting, etcOne-step compile and runDebuggingOrganization

Page 45: 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

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 www.eclipse.org• Get the “Eclipse IDE for Java Developers”

• Others often used with Java include NetBeans, JBuilder, many others

Page 46: 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

Eclipse IDE

46

IDE = Integrated Development EnvironmentAn IDE provides services that make it easier for

you to programEditor with syntax checking, automatic formatting,

etcOne-step compile and runDebuggingOrganization

Page 47: 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

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 www.eclipse.orgGet the “Eclipse IDE for Java Developers”

Others often used with Java include NetBeans, JBuilder, many others

Page 48: 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

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, ORGet the JDK 8 and then follow the easy

instructions at https://wiki.eclipse.org/JDT/Eclipse_Java_8_Support_For_Kepler

Page 49: 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

Eclipse IDE

49

Create a new project in Eclipse and write a class

Page 50: 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

Eclipse: Create a Project

Page 51: 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
Page 52: 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

Add a Code Package

Page 53: 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

Add a class

Page 54: 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

Write code in the class

Page 55: 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

Run the project

At least one class must have a main()!

Page 56: 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
Page 57: 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

“Run Configurations” is critical

Page 58: 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

“Window/Preferences” contains many settings