0% found this document useful (0 votes)
10 views

Week9 Module8 JavaControlStructures Conditional

Uploaded by

Isaac esparrago
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Week9 Module8 JavaControlStructures Conditional

Uploaded by

Isaac esparrago
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

College of Computer Studies and Engineering

INFORMATION TECHNOLOGY DEPARTMENT


ITC c105 – Computer Programming using Java

Module 8
CONTROL STRUCTURES
Learning Objectives:
At the end of this lesson, the students shall be able to:

1. Learn how to use decision control structures (if, else, switch) which allows
selection of specific sections of code to be executed.
2. Create a Java program using different types of conditional Structures.

In the previous lesson, we have given examples of sequential programs,


wherein statements are executed one after another in a fixed order. In this section,
we will be discussing a control structure, which allows us to change the ordering of
how the statements in our programs are executed.

A control structure is a block of programming that analyzes variables and


chooses a direction in which to go based on given parameters.

Decision Control Structures


Specific blocks of code while skipping other sections.

if statement
The if-statement specifies that a statement (or block of code) will be
executed if and only if a certain boolean statement is true.

1|Page Compiled by: Prof. Mary Ann B. Taduyo, MAEd, MIT and Prof. RoelL C. Traballo, MSIT
College of Computer Studies and Engineering
INFORMATION TECHNOLOGY DEPARTMENT
ITC c105 – Computer Programming using Java

The if-statement has the form,


If (boolean_expression )
statement;

or

if (boolean_expression )

{
statement1;
statement2;
...
}

where, boolean_expression is either a boolean expression or


boolean variable.

For example, given the code snippet,


int grade = 68;
if( grade > 60 )
System.out.println("Congratulations!");

or

int grade = 68;


if( grade > 60 ){
System.out.println("Congratulations!");
System.out.println("You passed!");
}

2|Page Compiled by: Prof. Mary Ann B. Taduyo, MAEd, MIT and Prof. RoelL C. Traballo, MSIT
College of Computer Studies and Engineering
INFORMATION TECHNOLOGY DEPARTMENT
ITC c105 – Computer Programming using Java

Example 1:

//if statement

import java.util.Scanner;
public class IfSample1a {
public static void main(String args[]) {
Scanner scan = new
Scanner(System.in);
int grade;

System.out.print("Enter your grade: ");


grade = scan.nextInt();

if( grade >= 75 )


System.out.println("Congratulations!");
}}

Example 2:
//if statement
import java.util.Scanner;

public class IfSample1b {


public static void main(String args[]) {
Scanner scan = new
Scanner(System.in);
int grade;

System.out.print("Enter your grade: ");


grade = scan.nextInt();

if( grade >= 75 ) {


System.out.println("Congratulations!");
System.out.println("You passed…");
}}}

3|Page Compiled by: Prof. Mary Ann B. Taduyo, MAEd, MIT and Prof. RoelL C. Traballo, MSIT
College of Computer Studies and Engineering
INFORMATION TECHNOLOGY DEPARTMENT
ITC c105 – Computer Programming using Java
 if-else statement
The if-else statement is used when we want to execute a certain
statement if a condition is true, and a different statement if the condition is
false.
The if-else statement has the form,
if (boolean_expression)
statement;
else
statement;

or can also be written as,

if (boolean_expression)
{
statement1;
statement2;
...
}
else
{
statement1;
statement2;
...
}

For example, given the code snippet,

int grade = 68;


if( grade > 60 )
System.out.println("Congratulations!");
else
System.out.println("Sorry you failed");
or
int grade = 68;
if( grade > 60 ){
System.out.println("Congratulations!");
System.out.println("You passed!");
}
else {
System.out.println("Sorry you failed");
}

4|Page Compiled by: Prof. Mary Ann B. Taduyo, MAEd, MIT and Prof. RoelL C. Traballo, MSIT
College of Computer Studies and Engineering
INFORMATION TECHNOLOGY DEPARTMENT
ITC c105 – Computer Programming using Java

Example 1:
//if-else statement
import java.util.Scanner;
public class IfElseSample1a {
public static void main(String args[]) {
Scanner scan = new
Scanner(System.in);
int grade;

System.out.print("Enter your grade: ");


grade = scan.nextInt();

if( grade >= 75 )


System.out.println("Congratulations!");
else
System.out.println("Sorry!");
}}

Compiled by: Prof. Mary Ann B. Taduyo, MAEd, MIT and Prof. RoelL C. Traballo, MSIT
5|Page
College of Computer Studies and Engineering
INFORMATION TECHNOLOGY DEPARTMENT
ITC c105 – Computer Programming using Java
Example 2:
//if-else statement
import java.util.Scanner;

public class IfElseSample1b {


public static void main(String args[]) {
Scanner scan = new
Scanner(System.in);
int grade;

System.out.print("Enter your grade: ");


grade = scan.nextInt();

if( grade >=75 ) {


System.out.println("Congratulations!");
System.out.println("You passed!");
}
else {
System.out.println("Sorry!");
System.out.println("You failed");
}
}}

Example 3:
import java.util.Scanner;
public class IfElseSample2a {
public static void main(String args[]) {

String pass="jru";

if (pass=="jru")
System.out.println("accepted");
else
System.out.println("invalid");
}}

6|Page Compiled by: Prof. Mary Ann B. Taduyo, MAEd, MIT and Prof. RoelL C. Traballo, MSIT
College of Computer Studies and Engineering
INFORMATION TECHNOLOGY DEPARTMENT
ITC c105 – Computer Programming using Java
Example 4:
import java.util.Scanner;
public class IfElseSample2b {
public static void main(String args[]) {
String pass;
Scanner scan = new Scanner(System.in);

System.out.print ("Enter password: ");


pass = scan.next();

if (pass=="jru")
System.out.println("accepted");

else

System.out.println("invalid");

} }

Notice that “JRU” & “jru” as


sample input will both display
“invalid” output. (Review
reference variable)

Example 5:

import java.util.Scanner;
public class IfElseSample2c {
public static void main(String args[]) {
String pass;
Scanner scan = new Scanner(System.in);

System.out.print ("Enter password: ");


pass = scan.next();

if (pass.equals("jru"))
System.out.println("accepted");
else
System.out.println("invalid");
}}

7|Page Compiled by: Prof. Mary Ann B. Taduyo, MAEd, MIT and Prof. RoelL C. Traballo, MSIT
College of Computer Studies and Engineering
INFORMATION TECHNOLOGY DEPARTMENT
ITC c105 – Computer Programming using Java

Using equals() method


The equals() method compares two objects
for equality and returns true if they are equal.

Notice that it will only return to true value


if equals method is compared to the same
value with the same case (i.e.,
if(pass.equals(“jru”));

equals() Method
 Description
The method determines whether the Number object that invokes the
method is equal to the object that is passed as an argument.
 Syntax
public boolean equals(Object o)
 Parameters
Here is the detail of parameters −
 Any object.
 Return Value
 The method returns True if the argument is not null and is an
object of the same type and with the same numeric value. There
are some extra requirements for Double and Float objects that are
described in the Java API documentation.
 Example 6:

public class Test {


public static void main(String args[]) {
Integer x = 5;
Integer y = 10;
Integer z =5;
Short a = 5;

System.out.println(x.equals(y));
System.out.println(x.equals(z));
System.out.println(x.equals(a));
}}

 This will produce the following result:


Output
false
true
false
8|Page Compiled by: Prof. Mary Ann B. Taduyo, MAEd, MIT and Prof. RoelL C. Traballo, MSIT
College of Computer Studies and Engineering
INFORMATION TECHNOLOGY DEPARTMENT
ITC c105 – Computer Programming using Java
Example 7:
import java.util.Scanner;
public class IfElseSample2d {
public static void main(String args[]) {

String pass;
Scanner scan = new Scanner(System.in);

System.out.print ("Enter password: ");


pass = scan.next();

if (pass.equalsIgnoreCase("jru"))
System.out.println("accepted");
else
System.out.println("invalid");

}}

Using equalsIgnoreCase() method

The java.lang.String.equalsIgnoreCase() method compares this String to


another String, ignoring case considerations. Two strings are considered
equal ignoring case if they are of the same length and corresponding
characters in the two strings are equal ignoring case.

equalsIgnoreCase() Method
 Description
This method compares this String to another String, ignoring case
considerations. Two strings are considered equal ignoring case, if they are
of the same length, and corresponding characters in the two strings are
equal ignoring case.

 Syntax
public boolean equalsIgnoreCase(String anotherString)

 Parameters
Here is the detail of parameters –

 anotherString − the String to compare this String against.

 Return Value
This method returns true if the argument is not null and the
Strings are equal, ignoring case; false otherwise.

9|Page Compiled by: Prof. Mary Ann B. Taduyo, MAEd, MIT and Prof. RoelL C. Traballo, MSIT
College of Computer Studies and Engineering
INFORMATION TECHNOLOGY DEPARTMENT
ITC c105 – Computer Programming using Java
 Example 8:

public class Test {


public static void main(String args[]) {

String Str1 = new String("This is really not immutable!!");


String Str2 = Str1;
String Str3 = new String("This is really not immutable!!");
String Str4 = new String("This IS REALLY NOT IMMUTABLE!!");
boolean retVal;

retVal = Str1.equals( Str2 );


System.out.println("Returned Value = " + retVal );

retVal = Str1.equals( Str3 );


System.out.println("Returned Value = " + retVal );

retVal = Str1.equalsIgnoreCase( Str4 );


System.out.println("Returned Value = " + retVal );
}}

 This will produce the following result −

Output
Returned Value = true
Returned Value = true
Returned Value = true

 if-else-if statement
The statement in the else-clause of an if-else block can be another if-
else structure. This cascading of structures allows us to make more complex
selections.

The if-else if statement has the form,


if( boolean_expression1 )
statement1;
else if(boolean_expression2 )
statement2;
else
statement3;

10 | P a g e Compiled by: Prof. Mary Ann B. Taduyo, MAEd, MIT and Prof. RoelL C. Traballo, MSIT
College of Computer Studies and Engineering
INFORMATION TECHNOLOGY DEPARTMENT
ITC c105 – Computer Programming using Java

Take note that you can have many else-if blocks after an if-statement.
The else- block is optional and can be omitted. In the example shown above,
if oolean_expression1 is true, then the program executes statement1 and
skips the other statements. If boolean_expression2 is true, then the
program executes statement 2 and skips to the statements following
statement3.

For example, given the code snippet,

int grade = 68;


if( grade > 90 ){
System.out.println("Very good!");
}
else if( grade > 60 ){
System.out.println("Very good!");
}
else {
System.out.println("Sorry you failed");

11 | P a g e Compiled by: Prof. Mary Ann B. Taduyo, MAEd, MIT and Prof. RoelL C. Traballo, MSIT
College of Computer Studies and Engineering
INFORMATION TECHNOLOGY DEPARTMENT
ITC c105 – Computer Programming using Java

 Common Errors when using the if-else statements:


1. The condition inside the if-statement does not evaluate to
a boolean value. For example,
//WRONG
int number = 0;
if( number ){
//some statements here
}

The variable number does not hold a Boolean value.

2. Using = instead of == for


comparison. For example,
//WRONG
int number = 0;
if( number = 0 ){
//some statements here
}

This should be written as,


//CORRECT
int number = 0;
if( number == 0 ){
//some statements here
}
3. Writing elseif instead of else if.

public class Grade {


public static void main( String[] args ) {
double grade = 92.0;

if( grade >= 90 ){


System.out.println( "Excellent!" );
}
else if( (grade < 90) && (grade >= 80)){
System.out.println("Good job!" );
}
else if( (grade < 80) && (grade >= 60)){
System.out.println("Study harder!" );
}
else {
System.out.println(“Sorry, you failed”);
}
}}

12 | P a g e Compiled by: Prof. Mary Ann B. Taduyo, MAEd, MIT and Prof. RoelL C. Traballo, MSIT
College of Computer Studies and Engineering
INFORMATION TECHNOLOGY DEPARTMENT
ITC c105 – Computer Programming using Java

Example 1:
import javax.swing.JOptionPane;

class IfElseIfSample1a {
public static void main(String[] args) {
int testScore = 76;
char grade;

if (testScore >= 90) {


grade = 'A';
}
else if (testScore >= 80) {
grade = 'B';
}
else if (testScore >= 70) {
grade = 'C';
}
else if (testScore >= 60) {
grade = 'D';
}

else {

grade = 'F';
}
JOptionPane.showMessageDialog(null, "Grade = " + grade);
} }

13 | P a g e Compiled by: Prof. Mary Ann B. Taduyo, MAEd, MIT and Prof. RoelL C. Traballo, MSIT
College of Computer Studies and Engineering
INFORMATION TECHNOLOGY DEPARTMENT
ITC c105 – Computer Programming using Java

Example 2:
import javax.swing.JOptionPane;

class IfElseIfSample1b {

public static void main(String[] args) {

int testScore;
char grade;

testScore = Integer.parseInt(JOptionPane.showInputDialog("Enter test score: "));

if (testScore >= 90) {


grade = 'A';
}
else if (testScore >= 80) {
grade = 'B';
}
else if (testScore >= 70) {
grade = 'C';
}
else if (testScore >= 60) {
grade = 'D';
}
else {
grade = 'F';
}
JOptionPane.showMessageDialog(null, "Grade = " + grade);
}}

14 | P a g e Compiled by: Prof. Mary Ann B. Taduyo, MAEd, MIT and Prof. RoelL C. Traballo, MSIT
College of Computer Studies and Engineering
INFORMATION TECHNOLOGY DEPARTMENT
ITC c105 – Computer Programming using Java

Example 3:

import java.io.*;
public class IfElseIfSample2 {
public static void main(String args[]) throws IOException{

BufferedReader br = new BufferedReader(


new InputStreamReader(System.in));
int grade;

System.out.print("Enter grade: ");


grade = Integer.parseInt(br.readLine());

if(grade > 100 || grade<50)


System.out.println("Invalid grade..");
else if(grade>74) {
System.out.println("Congrats");
System.out.println("you passed");
}
else {
System.out.println("Sorry");
System.out.println("you failed");
}
}}

15 | P a g e Compiled by: Prof. Mary Ann B. Taduyo, MAEd, MIT and Prof. RoelL C. Traballo, MSIT
College of Computer Studies and Engineering
INFORMATION TECHNOLOGY DEPARTMENT
ITC c105 – Computer Programming using Java

Example 3:

//************************************************************************
// MixedTypeInput
// This application demonstrates testing before reading to be
// sure to use the correct input method for the data.
//************************************************************************

import java.io.*;
import java.util.Scanner;

public class MixedTypeInput {


public static void main(String[] args){

double number;
Scanner in = new Scanner(System.in);

System.out.println("Enter your gross income: ");

if (in.hasNextInt())
{
number = (double)in.nextInt();
System.out.println("You entered " + number);
}
else if (in.hasNextFloat())
{
number = (double)in.nextFloat();
System.out.println("You entered " + number);
}
else if (in.hasNextDouble())
{
number = in.nextDouble();
System.out.println("You entered " + number);
}
else
System.out.println("Token not an integer or a real value.");
}}
Enter your gross
income: 55000
You entered 55000.0

Enter your gross


income: 55000.0
You entered 55000.0

Enter your gross


income: 55E10
You entered 5.50000001024E11

Enter your gross income:


Fifty Five Hundred
Token not an integer or a real value.

Compiled by: Prof. Mary Ann B. Taduyo, MAEd, MIT and Prof. RoelL C. Traballo, MSIT

You might also like