Handout 3 Control Statements + Exceptions
Handout 3 Control Statements + Exceptions
}
}
Multimethod greeting
package multimethodret;
public class MultiMethodRet {
public static void main(String[] args) {
String cb;
System.out.println("Hello");
cb=swah();
System.out.println(cb);
}
public static String swah() {
System.out.println("Habari");
return "comming back";
}
}
MultiMethods global variable
public class multiMethodScope {
static int nambari=100; //global class variable
public static void main(String[] args)
{
int num=250; // local method variable
System.out.println("greetings from Main method");
System.out.println("Global number is" + nambari);
System.out.println("Main method number is" + num);
Sub("konichwa");
}
}
if statements
If (condition)
Statement;
If they are no {} only one statement executed. Puts a
semi colon afer if for, do while, switch and while state
null statement is selected or repeated.
If(condition) {
Statement/s
}
If(condition) {
Statement/s;
} else {
Statements/s
}
If and else block have single statement the {}
delimiters can be removed
if else if
if (condition) {
statement/s
} else if(condition) {
Statement/s;
} else if(condition) {
Statements/s
} else if (condition)
Statement/s;
} else {
Statement/s;
}
Nested if statements
If students grade is greater or equal to 90
Print “a”;
Else If students grade is greater or equal to 87 print “A-”
Else If students grade is greater or equal to 84 print “B+”
Else If students grade is greater or equal to 79 print
“B”
Else If students grade is greater or equal to 96
print “OTHER”
Individual exercise Future exercise
Draw a UML activity diagram for above
pseudocode
Submit blackboard week5 Linkname
elseifPSwk4-1
grades
Marks>=90 A
Marks>=87 A-
Marks>=84 B+
Marks>=80 B
Marks>=76 B-
package gradeifelse;
public class GradeIfElse {
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
int marks;
System.out.println("Enter Marks:");
marks=input.nextInt();
if(marks>=90){
System.out.println("A");
} else if(marks>=87){
System.out.println("A-");
} else if(marks>=84){
System.out.println("B+");
} else if(marks>=80){
System.out.println("B");
} else {
System.out.println("OTHER");
}
}
}
PROGRAM THAT ASK USE TO ENTEER 10 STUDENTS MARKS AND GRADES THEM
package gradewhileifelse;
import java.util.Scanner;
public class GradeWhileIfElse {
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
int marks;
int control=0;
while(control<10) {
System.out.println("Enter Marks:");
marks=input.nextInt();
if(marks>=90){
System.out.println("A");
} else if(marks>=87){
System.out.println("A-");
} else if(marks>=84){
System.out.println("B+");
} else if(marks>=80){
System.out.println("B");
} else {
System.out.println("OTHER");
}
control=control+1;
} } }
Complete program submit blackboard week4 linkname usiugradingWK4
Do while
29
Syntax
switch(expression){
case constant-expression :
statement(s);
break; //optional
case constant-expression :
statement(s);
break; //optional
// you can have any number of case statements.
default : //Optional
statement(s);}
30
Switch program Exercise (don’t submit)
The following are names of detergents sold in a
shop
Omo, Sunlight, Msafi, Toss, Persil
switch(grade){
case 'A':
System.out.println("Grade is A");
break;
case 'B':
System.out.println("Grade is B");
break;
case 'C':
System.out.println("Grade is C");
Break;
case 'D':
System.out.println("Grade is D");
break;
case 'E':
System.out.println("Grade is E");
break;
default:
System.out.println("Grade invalid");
//break; // optional exits loop any way
} } }
Switch program READ char
package switchchar;
import java.util.Scanner;
public class SwitchChar {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter uppercase Grade A-F");
char grade=“C”
Grade =input.next().charAt(0);
switch(grade){
case 'A':
System.out.println("Grade is A");
break;
case 'B':
System.out.println("Grade is B");
break;
case 'C':
System.out.println("Grade is C");
break;
case 'D':
System.out.println("Grade is D");
break;
case 'E':
System.out.println("Grade is E");
break;
default:
System.out.println("Grade invalid");
//break; // optional exits loop any way
}
}
}
Break and continue statements
break cause control to get out loop or if or
else conditional statements
continue cause execution to go back to
beginning of loop cause statement after
continue to be skipped.
package dwconbrk;
} while(counter<=10);
}
}
}
Scanner reading char
char grade=sc.next().charAt(0);
• }
For program to display first 10 integers
package fordisp1_10;
public class ForDisp1_10 {
public static void main(String[] args) {
for(int i=1; i<=10;i++) {
System.out.println(i);
}
i=i+1
}
}
for statement
for statement executing single statement
for(initialization_exp; control_exp; increment-
decremexp)
(statement);
package fordisp1_10;
public class ForDisp1_10 {
public static void main(String[] args) {
}
}
Output of Nested for program
k=1 i=1
k=1 i=2
k=1 i=3
k=2 i=1
k=2 i=2
k=2 i=3
k=3 i=1
k=3 i=2
k=3 i=3
k=4 i=1
k=4 i=2
k=4 i=3
Nested individual while loop exercise
Math.pow(x,y)
Example 84
double num1=8, pow=4, prod=0;
prod=Math.pow(num1, pow);
System.out.println(prod);
Exception handling
• Java has Exception handlers
• Java exception handling based on that of C++, but
designed to be more in line with object oriented
paradigm. Further more Java has predefined exceptions
while C++ doesn’t
• Java has several classes for exception handling. All
exceptions in java are descendant of Throwable class.
Throwable is great grand parent of all exception classes.
• Throwable has two predefined sub classes : Error and
Exception.
• The Error class and descendants handle errors throw by
Java Virtual machine such as running out of heap
memory.
• These exceptions are never thrown to user program and
should never be handled there.
When to use Exception handling
try {
Statements that may cause exceptions
} catch(exceptiontype exceptionobj) {
Exception handling statements
} final {
This statement are always executed
}
Exception handling
}
ArithmeticException looping Program
package arithexcept;
import java.util.Scanner;
public class ArithExcept {
public static void main(String[] args) {
int num1, num2, divtot;
num1=15; num2=-4; divtot=0;
while(num1>num2){
try {
divtot=num1/num2;
} catch(ArithmeticException e) {
System.out.println("Error - "+e.getMessage());
System.exit(-1); // in you comment program executin continues
}
System.out.println("result:"+divtot);
num2=num2+1;
}
}
}
ArithmeticException +NumberFormatException
package arnofmtexcept;
import java.util.Scanner;
public class ArnofmtExcept {
public static void main(String[] args) {
int num1=10,num2=0;
double prod=0;
String snum2;
Scanner ingisha=new Scanner(System.in);
System.out.println("Enter String");
snum2=ingisha.next();
try {
num2=Integer.parseInt(snum2);
prod=num1/num2;
} catch(ArithmeticException ea){
System.out.println("artithmetic Exception Message "+ea.getMessage());
} catch(NumberFormatException en){
System.out.println("Format Exception Message "+en.getMessage());
}
}
}
Types of exceptions
The two types of exceptions: checked and
unchecked exception
Checked exceptions must be checked in
programs otherwise program throws an error.
Unchecked errors the programmer can ignore
and no errors.
ArithmeticException and NumberFormatException
are unchecked exceptions. Unchecked
exceptions extend RuntimeException and
Error classes
ArrayIndexOutBoundsException – catches
errors when array index is beyond the range
of index
Types of exceptions
When method occurs in a method we
have two choices:
1 handle exception by catch block
2. Declare program method throws
exception
- Throwing exception means method is
one that throws exception
- If we can deal with exception
effectively in method catch is
better if we cannot throw.
Throws program
package susha;
public class Susha {
Copy above program and Modify program so that it ask user to also enter
number of employees he/she wants to calculate tax and uses a for loop to
calculate and display tax
Submit by beginning of Monday 3-10-2022 next class blackboard week4 link
TaxcalcLoop
{method local and class
global variable
shadowing – program to
be made available later}
Exercise write a program with
two methods main() and swah().
Main calls swah and swah
returns a string when its ending
Both display location messages
in main, ndani swah
Main displays message returned
by swah
Class program
Class name PayrollGrossPay
write a program with two methods main()
and calcGPay() methods. Main calls
calcGPay() and calcGPay() will calculate
grosspay and return gross salary
Main displays message returned by
calcGPay()
Effects to observer:
• static
• Local and global variables
Write a program that uses
switch statement to determine
whether the range of integer
entered is with.
1-9
21-29
31-39
…
90-99
Not within 0-100 – displays “other”
package switcher;
import java.util.Scanner;
public class Switcher {
public static void main(String[] args) {
int inum=0, idiv=10;
Scanner sc=new Scanner(System.in);
boolean check=true;
while(check){
System.out.println("Enter integer inum1>0 and <100");
inum=sc.nextInt();
if(inum<=0){
System.out.println("Error \n");
check=true;
// System.exit(0); // causes normal program termination
//System.exit(n); n positive integer causes abnormal program
//termination
} else
check=false;
}
..program continued from previous page
switch(inum/idiv) {
case 0:
System.out.println("\n1-9");
break;
case 1:
System.out.println("\n10-19");
break;
case 2:
System.out.println("\n20-29");
break;
case 3:
System.out.println("\n30-39");
break;
default:
System.out.println("\nother");
}
}
}
System.exit()
System.exit(0);- causes
normal program
termination
System.exit(n); n positive
integer causes abnormal
program termination