conditionals - nc state computer science · 2019. 1. 31. · another if/else example • write code...

32
Condi tionals •if Statements •if-else Statements •Relational Operators •Multiple if Statements Sequential Nested • Factoring Code • Loop Techniques Loops with if-else Cumulative Sum/Multiplication fencepost Loops min/max Loops

Upload: others

Post on 03-Sep-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

Conditionals•if Statements

•if-else Statements

•Relational Operators

•Multiple if Statements• Sequential• Nested

• Factoring Code • Loop Techniques

• Loops with if-else

• Cumulative Sum/Multiplication

• fencepost Loops

• min/max Loops

Page 2: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

Copyright 2006 by Pearson Education 2

The if statement◼ 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> ;

<statement> ;

...

<statement> ;

}

Page 3: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

Example if Statement

• Write a program that accepts applications to graduate school if the student’s GPA is >= 3.0.

Scanner console = new Scanner(System.in);

System.out.print("GPA: ");

double gpa = console.nextDouble();

if (gpa >= 3.0) {

System.out.println("Application

}

accepted");

3

Page 4: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

Copyright 2006 by Pearson Education 9

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 it is false.

◼ General syntax:if (<condition>) {

<statement(s)>} else {

<statement(s)>}

;

;

Page 5: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

Example if/else Statement

• Write a program that accepts applications to graduate school if the student’s GPA is >= 3.0. Otherwise, tell the student they are on thewaiting list.

Scanner console = new Scanner(System.in);

System.out.print("GPA: ");

double gpa = console.nextDouble();

if (gpa >= 3.0) {

System.out.println("Application

} else {

accepted");

System.out.println("On the waiting list");

}

10

Page 6: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

Another if/else Example

• Write code to read an integer from the user and print whether it is

even or odd using an if/else statement.

– Example executions:Type an integer: 42Your number is even

Type an integer: 17

Your number is odd

Scanner console = new Scanner(System.in);

11

System.out.print("Type an integer: ");

int number = console.nextInt();

if (number % 2 == 0) {

System.out.println("Your number

} else {

System.out.println("Your number

}

is even");

is odd");

Page 7: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

Copyright 2006 by Pearson Education 4

Relational expressions◼ The <condition> used in an if or if/else statement is

the same kind seen in a for loop.for (int i = 1; i <= 10; i++) {

◼ The conditions are actually of type boolean

◼ These conditions are called relational expressionsand 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 >= 5 true

Page 8: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

Multiple if Statements

• Sequential if Statements

• Nested if Statements

– ending with else

– ending with else if

Page 9: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

Sequential if Statements• Choose 0, 1, or many paths through the code

– Conditions and the associated actions areindependent

if (<condition>1) {

<statement1>;

}

if (<condition2>) {

<statement2>;

}

if (<condition3>) {

<statement3>;

}

13

Page 10: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

Nested if/else Statements

• Chooses between many outcomes using manyconditions

• Can end in an else or and if

– else: Choose one of many paths

– else if: Choose one or 0 of many paths

CSC116: Intro to Java Programming © Sarah Heckman

14

Page 11: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

if/else if/else if

if (<condition>) {

<statement(s)> ;} else if (<condition>) {

<statement(s)> ;} else if (<condition>) {

<statement(s)> ;}

Example:

if (place == 1) {

System.out.println("First ");

} else if (place == 2) {

System.out.println("Second ");

} else if (place == 3) {

System.out.println("Third ");

}Are there any cases where this code will not print a message?

How could we modify it to print a message to non-medalists?

15

Page 12: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

if/else if/else

if (<condition>) {<statement(s)> ;

} else if (<conditio<statement(s)> ;

} else {

}

n>) {

<statement(s)> ;

Example:if (num < 0) {

System.out.println("Negative");} else if (num > 0) {

System.out.println("Positive");} else {

System.out.println("Zero");}

16

Page 13: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

Which if Structure to Use

• if/else

– Choose one of 2 paths

• if/else if/else

– Choose 1 of many paths

• if/else if/else if

– Choose 0 or 1 of many paths

• sequential if

– Choose 0, 1, or many of many paths: (conditions/actions are independent of each other)

Page 14: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

Which if/else Statement to use?

• Which if/else construct is most appropriate?– Reading the user's GPA and printing whether the student is

on the dean's list (3.8 to 4.0) or honor roll (3.5 to 3.8).

– Printing whether a number is even or odd.

– Printing whether a user is lower-class, middle-class, or upper-class based on their income.

– Reading a number from the user and printing whether it is divisible by 2, 3, and/or 5.

– Printing a user's grade of A, B, C, D, or F based on their percentage in the course.

18

Page 15: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

Copyright 2006 by Pearson Education 19

Which if/else answers◼ Which if/else construct is most appropriate?

◼ Reading the user's GPA and printing whether the student is onthe dean's list (3.8 to 4.0) or honor roll (3.5 to 3.8).

◼ nested if / else if

◼ Printing whether a number is even or odd.◼ simple if / else

◼ Printing whether a user is lower-class, middle-class, or upper-class based on their income.

◼ nested if / else if / else

◼ Reading a number from the user and printing whether it is divisible by 2, 3, and/or 5.

◼ sequential if / if / if

◼ Printing a user's grade of A, B, C, D, or F based on theirpercentage in the course.

◼ nested if / else if / else if / else if / else

Page 16: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

In-class Team Exercise (Individual for EOL section)

• Go to GitHub• Clone the csc116-xxx-Lab8-yy repository, where yy is your team repository number, xxx is your section number

– Copy the url to clone

– In exercises folder on local machine: git clone url

• Go to the moodle page and work on the Triangle.java assignment.• After creating the .java file according to the assignment, ONE team member:

– git add .

– git commit –m “message describing changes made”

– git push

• Remaining team members (every time any team member pushes something):

– git pull

Page 17: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

Triangle.java Exercise Details• Create a class Triangle that includes a static method named

getTriangleType().• The getTriangleType() method has three integer parameters

representing the lengths of the sides of a triangle and returns a String specifying the type of triangle that these sides form. The four types are:• equilateral - three sides of the same length• isosceles - two sides that are the same length• scalene - three sides of different lengths. • invalid - if passed values that do not form a valid triangle. The sides will not

form a valid triangle if the length of any side is >= the sum of the lengths of the other 2 sides, or if a side length is negative or zero.

• The main method should:• prompt the user for the lengths of the three sides of a triangle. You can

assume that the user always enters integers.• call the getTriangleType() method with the entered side lengths as parameters• print out the type of triangle formed by the entered

side lengths (which will be the value returned from the getTriangleType method call)

Page 18: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

Factoring if Statements

• Want to factor out code that is commonbetween nested if statements

– If the start of each branch is the same, move itbefore the if/else.

– If the end of each branch is the same, move itafter the if/else.

20

Page 19: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

Copyright 2006 by Pearson Education

Code in need of factoringif (money < 500) {

System.out.println("You have, $" + money + " left.");

System.out.print("Caution! Bet carefully.");

System.out.print("How much do you want to bet? ");

bet = console.nextInt();

} else if (money < 1000) {

System.out.println("You have, $" + money + " left.");

System.out.print("Consider betting moderately.");

System.out.print("How much do

bet = console.nextInt();

} else {

System.out.println("You have,

System.out.print("You may bet

you want to bet? ");

$" + money + " left.");

liberally.");

you want to bet? ");System.out.print("How much do

bet = console.nextInt();

}

Page 20: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

Copyright 2006 by Pearson Education

Code after factoring

System.out.println("You have, $" +

if (money < 500) {

money + " left.");

System.out.print("Caution! Bet carefully.");

} else if (money < 1000) {

System.out.print("Consider betting moderately.");

} else {

System.out.print("You may bet liberally.");

}

System.out.print("How much do

bet = console.nextInt();

you want to bet? ");

Page 21: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

}

Copyright 2006 by Pearson Education 24

Loops with if/else◼ Loops can be used with if/else statements:

int nonnegatives = 0, negatives = 0;

for (int i =

int next

if (next

1; i <= 10; i++) {

= console.nextInt();

>= 0) {

nonnegatives++;

} else {

negatives++;

}

}

public static void printEvenOdd(int max) {

for (int i = 1; i <= max; i++) {

if (i % 2 == 0) {

System.out.println(i +

} else {

System.out.println(i +

}

}

" is even");

" is odd");

Page 22: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

Cumulative Sum

• Write a program to calculate the sum of thefirst n integers

public static int sumTo(int

int sum = 0; //Initialize

n) {

variable to store sum

}

return sum;

}

25

for (int i = 0; i <= n; i++) {

sum += i;

Page 23: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

Cumulative Multiplicationpublic static int multiply(int n) {

//Create a variable to accumulate

//the result

int product = 1;

for (int i = 1; i <= n; i++

//Modify the accumulator

){

with value

product = product * i; //or product *= i;

}

//Return the accumulated value

return product;

}

26

Page 24: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

Cumulative Concatenation• Remember our NumberWriter exercise from Lab5:

– Write a method named printNumbers that accepts an

number (integer) as a parameter and prints each number

from 1 up to that number, inclusive, boxed by square

brackets.

• Instead of printing the numbers in the loop, let’s accumulate

a String using cumulative concatenation and then return the

String to the caller to print. Call the new method

createSequence:

public static String createSequence(int n) {

String result = ""; //initialize accumulator to empty String

for (int i = 1; i <= n; i++) {

result = result + "[" + i + "] ";

}

return result;

}

Page 25: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

Cumulative Sum Loops using if

• Calculate sum of odd numbers

public static void oddSum(Scanner console, int num) {

double sum = 0.0;

for (int i = 0; i < num; i++) {

System.out.print("Next num: ");

double next = console.nextDouble();

if (next % 2 != 0) {

sum += next;

}

}

System.out.println("Sum of Odds: " + sum);

}

27

Page 26: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

Fencepost Loops

• Example– Cumulative String

• Comma separated list

"1, 2, 3, 4, 5"

• Print out of addition of many numbers

"1 + 2 + 3 + 4 + 5"

28

Page 27: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

Fencepost Loops (one method)

//The first fence post is printed

//BEFORE the loop

System.out.print(1);

for (int i = 2; i <=

System.out.print("

5; i++) {

+ " + i);

}

System.out.println();

29

Page 28: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

Fencepost Loops (another method)

//The same output

//last fence post

//the loop

as before,

is printed

but the

AFTER

for (int i = 1; i < 5;

System.out.print(i +

i++) {

" + ");

}

System.out.println(5);

30

Page 29: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

Fencepost Loops using if

for (int i = 1; i <= 5;

System.out.print(i);

if (i < 5) {

i++) {

System.out.print(" + ");

}

}

System.out.println();

31

Page 30: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

Min/Max Loops using if• Write a loop to that returns the maximum and minimum of 5 numbers

that a user enters

Scanner

public static void main(String[] args) {

in = new Scanner(System.in);

int max = 0;

int min = 0;

for (int i = 0; i < 5; i++)

{System.out.print("Type an Integer: ");

int temp

if (i ==

max =

min =

}

= in.nextInt();

0) {

temp;

temp;

else if (temp > max) {

max = temp;

}

else if (temp < min) {

min = temp;

}

}

System.out.println("Max: " +

System.out.println("Min: " +

max);

min);

}

Page 31: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

Another Method to find min/max

• Write a loop to that returns the maximum number and minimum of 5numbers that a user enters

public static

Scanner in

void main(String[] args) {

= new Scanner(System.in);

for (int i = 0; i < 5; i++) {

System.out.print("Type an Integer: ");

int temp

if (temp

max =

}

if (temp

min =

}

= in.nextInt();

> max) {

temp;

< min) {

temp;

}

System.out.println("Max:

System.out.println("Min:

" + max);

" + min);

}

33

int max = Integer.MIN_VALUE;

int min = Integer.MAX_VALUE;

Page 32: Conditionals - NC State Computer Science · 2019. 1. 31. · Another if/else Example • Write code to read an integer from the user and print whether it is even or odd using an if/else

In-class Exercise• Create a class named SumPrinter.

• In this class, write a method called fractionSum that accepts an integer parameter n (can assume n > 0) and returns a String containing the first n terms of the sequence:

• Your method will help you practice the following concepts:

• Cumulative Concatenation algorithms

• Fencepost algorithms

• Put the following main method in your program - the comments display what should be printed to the console window.

public static void main(String[] args) { System.out.println (fractionSum(2)); // 1 + (1/2) System.out.println (fractionSum(4)); // 1 + (1/2) + (1/3) + (1/4) System.out.println (fractionSum(5)); // 1 + (1/2) + (1/3) + (1/4) + (1/5)

}