Download 04b-if_return

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CSE 142 Lecture Notes
Conditional Execution with if Statements;
Methods that Return Values (briefly)
Chapters 3 and 4
Suggested reading: 3.3-3.4; 4.4-4.9
Suggested self-checks: Section 3.9 #5-7, 11-12, 18;
Section 4.10 #5-23
These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or
modified without Marty Stepp's expressed written permission. All rights reserved.
1
Conditional Execution
The if statement
The if/else statement
2
The if statement


Programs that read user input often want to take
different actions depending on the values of the user's
input.
if statement: A Java statement that executes a block
of statements only if a certain condition is true.



If the condition is not true, the block of statements is skipped.
General syntax:
if (<condition>) {
<statement(s)> ;
}
Example:
int gpa = console.nextDouble();
if (gpa <= 2.0) {
System.out.println("Your application is denied.");
}
3
The if/else statement

if/else statement: A Java statement that executes one block of
statements if a certain condition is true, and a second block of
statements if the condition is not true.


General syntax:
if (<condition>) {
<statement(s)> ;
}
else {
<statement(s)> ;
}
Example:
int gpa = console.nextDouble();
if (gpa <= 2.0) {
System.out.println("Your application is denied.");
}
else {
System.out.println("Welcome to Mars University!");
}
4
Relational expressions

The <condition> used in an if or if/else statement is
the same kind of value seen in the middle of a for loop.



for (int i = 1; i <= 10; i++)
These conditions are called relational expressions.
Relational expressions use one of the following six
relational operators:
Operator
Meaning
Example
Value
==
equals
1 + 1 == 2
true
!=
does not equal
3.2 != 2.5
true
<
less than
10 < 5
false
>
greater than
10 > 5
true
<=
less than or equal to
126 <= 100
false
>=
greater than or equal to 5.0 >= 5.0
true
5
Evaluating rel. expressions


The relational operators can be used in a bigger expression with
the mathematical operators we learned earlier.
Relational operators have a lower precedence than mathematical
operators, so they are evaluated last.

Example:
5 * 7
5 * 7
35
35
true

>=
>=
>=
>=
3 + 5 * (7 - 1)
3 + 5 * 6
3 + 30
33
Relational operators cannot be "chained" in the way that you have
seen in algebra.

Example:
2 <= x <= 10
true
<= 10
error!
6
Nested if/else statements

Nested if/else statement: A chain of if/else that can select
between many different outcomes based on several conditions.


General syntax (shown with three different outcomes, but any number
of else if statements can be added in the middle):
if (<condition>) {
<statement(s)> ;
} else if (<condition>) {
<statement(s)> ;
} else {
<statement(s)> ;
}
Example:
int grade = console.nextInt();
if (grade >= 90) {
System.out.println("Congratulations! An A!");
} else if (grade >= 80) {
System.out.println("Your grade is B. Not bad.");
} else if (grade >= 70) {
System.out.println("You got a C. Work harder!");
}
7
Structures of if/else code

Choose 1 of many paths:

Choose 0, 1, or many of many paths:
(use this when the conditions are
mutually exclusive)
if (<condition>) {
<statement(s)>;
} else if (<condition>) {
<statement(s)>;
} else {
<statement(s)>;
}

Choose 0 or 1 of many paths:
(use this when the conditions are mutually
exclusive and any action is optional)
if (<condition>) {
<statement(s)>;
} else if (<condition>) {
<statement(s)>;
} else if (<condition>) {
<statement(s)>;
}
(use this when the conditions/actions are independent of each other)
if (<condition>) {
<statement(s)>;
}
if (<condition>) {
<statement(s)>;
}
if (<condition>) {
<statement(s)>;
}
8
Comparing objects


The relational operators such as < and == only behave
correctly on primitive values.
Objects such as String, Point, and Color can be
compared for equality by calling a method named
equals.


Example (incorrect):
String name = console.next();
if (name == "Teacher") {
System.out.println("You must be a swell guy!");
}
Example (correct):
String name = console.next();
if (name.equals("Teacher")) {
System.out.println("You must be a swell guy!");
}
9
String condition methods

There are several methods of a String object that can
be used as conditions in if statements:
Method
Description
equals(String)
whether two Strings contain exactly the
same characters
equalsIgnoreCase(String)
whether two Strings contain the same
characters, ignoring upper vs. lower
case differences
startsWith(String)
whether one String contains the other's
characters at its start
endsWith(String)
whether one String contains the other's
characters at its end
10
String condition examples
Scanner console = new Scanner(System.in);
System.out.print("Type your full name and title: ");
String name = console.nextLine();
if (name.endsWith("Ph. D.")) {
System.out.println("Hello, doctor!");
}
if (name.startsWith("Ms.")) {
System.out.println("Greetings, Ma'am.");
}
if (name.equalsIgnoreCase("marty stepp")) {
System.out.println("Welcome, master! Command me!");
}
if (name.toLowerCase().indexOf("jr.") >= 0) {
System.out.println("Your parent has the same name!");
}
11
Conditions and Scanner

A Scanner object has methods that can be used to test
whether the upcoming input token is of a given type:
Method
Description
hasNext()
Whether or not the next token can be read as a
String (always true for console input)
hasNextInt()
Whether or not the next token can be read as an
int
hasNextDouble()
Whether or not the next token can be read as a
double
hasNextLine()
Whether or not the next line of input can be read
as a String (always true for console input)

Each of these methods waits for the user to type input
tokens and press Enter, then reports a true or false
answer.
12
Scanner condition example

The Scanner's hasNext___ methods are very useful for testing
whether the user typed the right kind of token for our program to
use, before we read it (and potentially crash!).
Scanner console = new Scanner(System.in);
System.out.print("How old are you? ");
if (console.hasNextInt()) {
int age = console.nextInt();
System.out.println("Retire in " + (65 - age) + " years.");
} else {
System.out.println("You did not type an integer.");
}
System.out.print("Type 10 numbers: ");
for (int i = 1; i <= 10; i++) {
if (console.hasNextInt()) {
System.out.println("Integer: " + console.nextInt());
} else if (console.hasNextDouble()) {
System.out.println("Real number: " + console.nextDouble());
}
}
13
Methods that Return Values
Java's Math class
Writing methods that return values
14
Java's Math class


Java has a class called Math that has several useful
methods that perform mathematical calculations.
Method name
Description
abs(value)
absolute value
cos(value)
cosine, in radians
log(value)
logarithm base e
max(value1, value2)
larger of two values
min(value1, value2)
smaller of two values
pow(value1, value2)
value1 to the value2 power
random()
random double between 0 and 1
round(value)
round to nearest whole number
sin(value)
sine, in radians
sqrt(value)
square root
The Math methods are called by writing:
Math. <name> ( <values> )
15
Methods that "return" values

The methods of the Math class do not print their results
to the console.



Instead, a call to one of these methods can be used as an
expression or part of an expression.
The method evaluates to produce (or return) a numeric result.
The result can be printed or used in a larger expression.
Example:
double squareRoot = Math.sqrt(121.0);
System.out.println(squareRoot);
// 11.0

int absoluteValue = Math.abs(-50);
System.out.println(absoluteValue);
// 50
System.out.println(Math.min(3, 7) + 2);
// 5
16
Methods that return values

Declaring a method that returns a value:
public static <type> <name> ( <type> <name> ) {
<statement(s)> ;
}

Returning a value from a method:
return <value> ;

Example:
// Returns the given number cubed (to the third power).
public static int cube(int number) {
return number * number * number;
}
17
Behavior of return

Just as parameters let you pass information into a
method from outside, return values let you pass
information out from a method to its caller.
The method call can be used as an expression. The method call
'evaluates' to be the number/value that you return.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int square = getNumber(console);
}

public static int getNumber(Scanner console) {
System.out.print("Enter a number: ");
int number = console.nextInt();
return number * number;
}
18
Example returning methods
// Converts Fahrenheit to Celsius.
public static double fToC(double degreesF) {
return 5.0 / 9.0 * degreesF - 32;
}
// Converts Celsius to Fahrenheit.
public static double cToF(double degreesC) {
return 9.0 / 5.0 * degreesC + 32;
}
// Converts kilograms to pounds.
public static int factorial(int n) {
int product = 1;
for (int i = 1; i <= n; i++) {
product = product * i;
}
return product;
}
19