• Tidak ada hasil yang ditemukan

SELECTION STATEMENTS (3)

N/A
N/A
Protected

Academic year: 2025

Membagikan "SELECTION STATEMENTS (3)"

Copied!
25
0
0

Teks penuh

(1)

Control Statement Examples

GC 201

(2)

The if Statement

With a block of statements –

Write a program that identifies the students who didn’t pass the course.

The program should also print an appropriate message.

INPUT Student’s score (variable: score, type: double) OUTPUT Letter grade = ‘F’ (variable: grade, type: char)

Print an appropriate message PROCES

S if (score <60) 1) grade = ‘F’

2) Print “Failed”

FLOWCHART

Start

Read score

score < 60?

True grade = ‘F’

NOTE THAT

grade = ‘X’

(3)

With a block of statements - CODE

// import necessary libraries

import java.util.*; //contains the class Scanner public class ifStatementN

{

// instantiate the object console from the class Scanner static Scanner console = new Scanner (System.in);

public static void main (String[] args) {

// Declaration section: to declare needed variables double score;

char grade = ‘X’; //initialize grade // Input section: to enter values of used variables

System.out.println (“Enter student’s score”); //prompt score = console.nextDouble();

// Processing section: processing statements

if (score < 60.0) // score is double {

grade = ‘F’;

System.out.println (“Failed”);

} //end if(score < 60.0)

// Output section: display program output

System.out.printf (“Student’s Grade = %3c“, grade);

} // end main 1

2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

The if Statement

(4)

With a block of statements - PROGRAM : CASE 1 (TRUE)

The if Statement

Enter student’s score 50.5_

1 2

double score;

char grade = ‘X’;

//initialize grade

10

11

50.5

score grade

X

System.out.println (“Enter student’s score”); //prompt score = console.nextDouble();

13 14

???

score grade

X

(5)

50.5 F With a block of statements - PROGRAM : CASE 1 (TRUE)

The if Statement

if (score < 60.0)

// score is double {

grade = ‘F’;

System.out.println (“Failed”); //output line 3 } //end if (score < 60.0)

16 17 18 19 20

50.5

score grade

F

System.out.printf (“Student’s Grade = %3c“, grade); //output line 4

22

Enter student’s score 50.5

Failed_

1 2 3

Enter student’s score 50.5

Failed

Student’s Grade = ~~F_

1 2 3 4

(6)

With a block of statements: PROGRAM : CASE 2 (FALSE)

The if Statement

Enter student’s score 85_

1 2

double score;

char grade = ‘X’;

//initialize grade

10

11

85.0

score grade

X

System.out.println (“Enter student’s score”); //prompt score = console.nextDouble();

13 14

???

score grade

X

(7)

85.0

score grade

X

With a block of statements - PROGRAM : CASE 2 (FALSE)

The if Statement

if (score < 60.0)

// score is double {

grade = ‘F’;

System.out.println (“Failed”);

} //end if (score < 60.0)

16

17 18 19 20

85.0

score grade

X

System.out.printf (“Student’s Grade = %3c“, grade);

22

Enter student’s score 85_

1 2

Enter student’s score 85

Student’s Grade = ~~X_

1 2 3

(8)

The if…else Statement

With a single statement – PROGRAM : ANALYSIS

Write a program that calculates the net salary after taxes deduction. If the salary is greater than 5000 SR, taxes are 20% of the salary;

otherwise, taxes are 25% of the salary.

INPUT Salary (variable: salary, type: double)

OUTPUT Net Salary (variable: netSalary, type: double) PROCES

S if (salary > 5000) netSalary=0.8*salary;

if (salary <= 5000) netSalary=0.75*salary.

(9)

The if…else Statement

With a single statement – PROGRAM : Flowchart

Start Read salary

salary >

5000?

netSalary = 0.8 * salary True

netSalary = 0.75 * salary

Print netSalary

False

(10)

With a single statement - PROGRAM : CODE

// import necessary libraries

import java.util.*; //contains the class Scanner public class ifElseStatement1

{

// instantiate the object console from the class Scanner static Scanner console = new Scanner (System.in);

public static void main (String[] args) {

// Declaration section: to declare needed variables double salary, netSalary;

// Input section: to enter values of used variables

System.out.println (“Enter employee’s salary”); //prompt salary = console.nextDouble();

// Processing section: processing statements

if (salary > 5000.0) // salary is double netSalary = 0.8 * salary;

else

netSalary = 0.75 * salary;

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

The if…else Statement

(11)

With a single statement - PROGRAM : CASE 1 (TRUE)

The if…else Statement

Enter employee’s salary 6000_

1 2

System.out.println (“Enter employee’s salary”); //prompt score = console.nextDouble();

12 13

if (salary > 5000.0)

// salary is double

netSalary = 0.8 * salary; //condition is true

else

netSalary = 0.75 * salary;

15 16 17 18

Enter employee’s salary 6000_

1 2

System.out.printf (“Net Salary = %.2f“, netSalary); //output line 3

20

Enter employee’s salary 6000

Net Salary = 4800.00_

1 2 3

(12)

With a single statement - PROGRAM : CASE 2 (FALSE)

The if…else Statement

Enter employee’s salary 2500.0_

1 2

System.out.println (“Enter employee’s salary”); //prompt score = console.nextDouble();

12 13

if (salary > 5000.0)

// salary is double netSalary = 0.8 * salary;

else

netSalary = 0.75 * salary; //condition is false

15

16 17 18

Enter employee’s salary 2500.0_

1 2

System.out.printf (“Net Salary = %.2f“, netSalary); //output line 3

20

Enter employee’s salary 2500.0

Net Salary = 1875.00_

1 2 3

(13)

The switch Statement

EXAMPLE 2

Write a program that displays the following menu, then acts accordingly:

Enter your choice:

1. Add two positive numbers

2. Get the double of a positive number 3. Get the square of a number

The program should give an error message for invalid inputs.

(14)

The switch Statement

EXAMPLE 2

public static void main (String[] args) {

//Declaration section

Scanner read = new Scanner (System.in);

int choice, num1, num2, result = -1;

String message = “Invalid input”;

//input section //Display menu

System.out.println (“Enter your choice:”);

System.out.println (“1. Add two positive numbers”);

System.out.println (“2. Get the double of a positive number”);

System.out.println (“3. Get the square of a number”);

choice = read.nextInt();

//processing section 1

2 3 4 5 6 7 8 9 10 11 12 13 14

(15)

The switch Statement

EXAMPLE 2 (cont’d)

//processing section switch (choice) {

case 1: System.out.println (“Enter two positive integers”); //prompt num1 = read.nextInt();

num2 = read.nextInt();

result = num1 + num2; // the value of result is no more equal to -1

break;

case 2: System.out.println (“Enter a positive integer”); //prompt num1 = read.nextInt();

result = num1 * 2; // the value of result is no more equal to -1 break;

case 3: System.out.println (“Enter an integer”); //prompt num1 = read.nextInt();

result = num1 * num1; // the value of result is no more equal to -1 break;

default: message =“Invalid value of choice”; //no change to “result”  result=-1 } //end switch

//output section if (result !=-1)

System.out.println (result); //result is modified (!= -1) else

System.out.println (message); //result is not modified (equals -1) 14

15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

(16)

Without default Statement EXAMPLE 2

In fact, line 30 in slide 10 adds nothing to the program. Note that the variable message is already initialized to “Invalid input” in line 6.

In addition, the default is optional in the switch statement. In other words, it may be omitted from the switch statement if it is useless  Therefore, line 30 may be omitted.

The modified “Processing section” of the program is shown in

the next slide:

(17)

Without default Statement EXAMPLE 2

//processing section switch (choice) {

case 1: System.out.println (“Enter two positive integers”); //prompt num1 = read.nextInt();

num2 = read.nextInt();

result = num1 + num2; // the value of result is no more equal to -1

break;

case 2: System.out.println (“Enter a positive integer”); //prompt num1 = read.nextInt();

result = num1 * 2; // the value of result is no more equal to -1 break;

case 3: System.out.println (“Enter an integer”); //prompt num1 = read.nextInt();

result = num1 * num1; // the value of result is no more equal to -1 break;

} //end switch //output section if (result !=-1)

System.out.println (result);

else

System.out.println (message);

14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35

(18)

EXAMPLE 2 – Validating user input

//processing section switch (choice) {

case 1: System.out.println (“Enter two positive integers”); //prompt num1 = read.nextInt();

num2 = read.nextInt();

if ((num1 < 0) || (num2 < 0)) //should be made after reading num1 & num2 result = -1;

else

result = num1 + num2; // the value of result is no more equal to -1

break;

case 2: System.out.println (“Enter a positive integer”); //prompt num1 = read.nextInt();

if (num1 < 0) //this should be made after reading num result = -1;

else

result = num1 * 2; // the value of result is no more equal to -1 break;

14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

Programming Hint (1)

(19)

Programming Hint (1)

EXAMPLE 2 – Validating user input (cont’d)

//output section if (result !=-1)

System.out.println (result);

else

System.out.println (message);

} //end main 37

38 39 40 41 42

In the example above, result is used to store the result of the arithmetic operation. It is also used to denote an invalid input. The sources of invalid inputs may be either the variable choice, num1 or num2.

Initially, result is initialized to -1 (line 5). This is useful in case the user entered an invalid value for the variable choice.

Now, let us reconsider the conditions in lines 20 and 27. In fact, these may be re-written in a smarter way as follows:

Validating user input is a vital issue in programming. The

programmer should take into consideration all possible values

entered by the user.

(20)

Programming Hint (1)

EXAMPLE 2 - Validating user input (cont’d)

case 1: System.out.println (“Enter two positive integers”); //prompt num1 = read.nextInt();

num2 = read.nextInt();

if ((num1 >= 0) && (num2 >= 0))

result = num1 + num2; // the value of result is no more equal to -1

break;

17 18 19 20 21 22

case 2: System.out.println (“Enter a positive integer”); //prompt num1 = read.nextInt();

if (num1 >= 0)

result = num1 * 2; // the value of result is no more equal to -1 break;

25 26 27 28 29

We were able to omit lines 21, 22 and lines 28, 29 in slide 13

since they add nothing to the logic. However, we had to modify

the logical expressions as shown above.

(21)

EXAMPLE 2 – Reducing Redundancy

System.out.println (“Enter a positive integer”);

num1 = read.nextInt();

//processing section switch (choice) {

case 1: System.out.println (“Enter a positive integer”); //prompt num1 = read.nextInt();

num2 = read.nextInt();

if ((num1 < 0) || (num2 < 0)) //should be made after reading num1 & num2 result = -1;

else

result = num1 + num2; // the value of result is no more equal to -1

break;

case 2: System.out.println (“Enter a positive integer”); //prompt num1 = read.nextInt();

if (num1 < 0) //this should be made after reading num result = -1;

else

result = num1 * 2; // the value of result is no more equal to -1 break;

case 3: System.out.println (“Enter an integer”); //prompt num1 = read.nextInt();

result = num1 * num1; // the value of result is always positive 14

15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

Programming Hint (2)

(22)

Programming Hints

EXAMPLE 2 – Final version

public static void main (String[] args) {

//Declaration section

Scanner read = new Scanner (System.in);

int choice, num1, num2, result = -1;

String message = “Invalid input”; //this may also be declared as a constant //input section

//Display menu

System.out.println (“Enter your choice:”);

System.out.println (“1. Add two positive numbers”);

System.out.println (“2. Get the double of a positive number”);

System.out.println (“3. Get the square of a number”);

choice = read.nextInt();

System.out.println (“Enter a positive integer”);

num1 = read.nextInt();

//processing section 1

2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

(23)

Programming Hint

EXAMPLE 2 – Final version (cont’d)

//processing section switch (choice) {

case 1: System.out.println (“Enter a positive integer”); //prompt num2 = read.nextInt();

if ((num1 >= 0) && (num2 >= 0))

result = num1 + num2; // the value of result is no more equal to -1

break;

case 2: if (num1 >= 0) //this should be made after reading num

result = num1 * 2; // the value of result is no more equal to -1 break;

case 3: result = num1 * num1; // the value of result is always positive break;

} //end switch //output section if (result != -1)

System.out.println (result);

else

System.out.println (message);

} //end main 16

17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35

(24)

Without break Statement

EXAMPLE 4

Using a switch statement, write a program that accepts an integer value

from the user ranging between -2 and 2. The program then identifies if

the number is negative, zero or positive.

(25)

Without break Statement

EXAMPLE 4 - SOLUTION

public static void main (String[] args) {

//Declaration section

Scanner read = new Scanner (System.in);

int num;

//input section

System.out.println (“Enter an integer between -2 and +2); //prompt num = read.nextInt();

//processing section switch (num)

{

case -2:

case -1: System.out.println (“The number is negative”);

break;

case 0: System.out.println (“The number is zero”);

break;

case 1:

case 2: System.out.println (“The number is positive”);

break;

default: System.out.println (“Invalid input”);

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

Referensi

Dokumen terkait

 Contoh berikut merupakan kasus yang serupa dengan kasus yang sudah dibahas untuk while dan do..while... public static void

Method yang digunakan pada program tersebut adalah public static void main (String []args){.. Static pada method main berarti metodh main tidak mengubah

public class Pertama adalah nama kelas yang kita buat (dalam java setiap membuat program berarti membuat sebuah kelas). public static void main(String args[]) adalah permulaan

3 package A; public class MainA { public static void mainString args[]{ } } package A; public class TestA { private int varPrivateA ; int varDefaultA ; protected int

import java.io.*; import java.util.*; public class LineNumberer { public static void mainString[] args throws FileNotFoundException { Scanner console = new ScannerSystem.in;

Java Application Menampilkan Tulisan //Welcome1.java Public class Welcome1 { //main method memulai eksekusi aplikasi java public static void main String args[] {

import java.util.Scanner; public class FinalExamA{ public static void mainString []args{ Scanner s=new ScannerSystem.in; System.out.println"Choose one of the

import java.util.Scanner; public class FinalExamB{ public static void mainString []args{ Scanner s=new ScannerSystem.in; System.out.println"Choose one of the