Sei sulla pagina 1di 71

Kolej Matrikulasi Pahang

Hands on Module
For Java Programming
SC025
2018/2019

i
Contents

CONTENTS

PRACTICAL 1: INTRODUCTION TO JAVA™ PROGRAMMING (4 HOURS) ....................1

Task 1: Using Java editor (jGRASP) ........................................................................................................... 1

Task 2: Use Output Statement to Display Messages ................................................................................ 5

Task 3: Displaying Formatted Output Using Escape Sequence \n and \t ........................................... 7

Task 4: Exercises ....................................................................................................................................... 8

PRACTICAL 2: DATA TYPES, OPERATORS, AND EXPRESSIONS (4 HOURS) ............... 9

Task 1: Displaying Values of Variables ...................................................................................................... 9

Task 2: Displaying Values of Variables Entered by User ......................................................................... 11

Task 3: Arithmetic Calculations .............................................................................................................. 12

Task 4: Using Relational Operators......................................................................................................... 13

Task 5: Using Relational and Logical Operators ...................................................................................... 14

Task 6: Exercise ....................................................................................................................................... 15

PRACTICAL 3: SEQUENCE CONTROL STRUCTURE (2 HOURS)................................... 16

Task 1: Find the square of a number entered by user ............................................................................ 16

Task 2: Calculate and display the average of three marks ..................................................................... 17

Task 3: Calculate and display the area of a rectangle............................................................................. 18

Task 4: Swapping values of two variables .............................................................................................. 19

Task 5: Adding two numbers .................................................................................................................. 20

Task 6: Difference between two numbers ............................................................................................. 22

Task 7: Calculate and display the average of three (3) marks entered by user. ..................................... 24

Task 8: Exercise ....................................................................................................................................... 25

PRACTICAL 4: SELECTION CONTROL STRUCTURE (2 HOURS) .................................. 26

Task 1: Single Selection using if statement ........................................................................................ 26

Task 2: Single Selection using if statement ........................................................................................ 27

ii
Contents

Task 3: Exercise ....................................................................................................................................... 28

Task 4: Dual Selection using if/else statement ............................................................................... 29

Task 5: Dual Selection using if/else statement ............................................................................... 30

Task 6: Dual Selection using if/else statement ............................................................................... 31

Task 7: Dual Selection using if/else statement ............................................................................... 32

Task 8: Exercise ....................................................................................................................................... 33

Task 9: Multiple Selection using if else/if statement .................................................................. 34

Task 10: Multiple Selection using if else/if statement .................................................................. 35

Task 11: Multiple Selection using if else if statement .................................................................. 36

Task 12: Exercise ....................................................................................................................................... 37

PRACTICAL 5: REPETITION CONTROL STRUCTURE (2 HOURS)................................. 38

Task 1: Repetition using while statement.......................................................................................... 38

Task 2: Repetition using while statement.......................................................................................... 39

Task 3: Repetition using while statement.......................................................................................... 39

Task 4: Repetition using while statement.......................................................................................... 40

Task 5: Repetition using for statement .............................................................................................. 41

Task 6: Exercise ....................................................................................................................................... 43

Task 7: Repetition using sentinel-controlled .......................................................................................... 44

Task 8: Exercise ....................................................................................................................................... 45

PRACTICAL 6: ARRAYS (6 HOURS) ..............................................................................46

Task 1: Declare and Enter Data into Arrays ............................................................................................ 46

Task 2: Accessing Elements in an Array .................................................................................................. 48

Task 3: Displaying Elements in an Array ................................................................................................. 49

Task 4: Linear Search .............................................................................................................................. 49

Task 5: Find Average ............................................................................................................................... 50

Task 6: Maximum ................................................................................................................................... 51

iii
Contents

Task 7: Frequency ................................................................................................................................... 52

Task 8: Exercise ....................................................................................................................................... 53

PRACTICAL 7: NON-STATIC METHODS (8 HOURS) .................................................... 54

Task 1: Understanding the Concept of Methods .................................................................................... 54

Task 2: A Method Accepting No Arguments and Returning No Value ................................................... 58

Task 3: A Method Accepting No Arguments and Returning No Value ................................................... 59

Task 4: A Method with Arguments and Returning No Value .................................................................. 60

Task 5: A Method with Arguments and Returning No Value .................................................................. 61

Task 6: A Method without Arguments and Returning Value .................................................................. 62

Task 7: A Method Accepting Arguments and Returning Value .............................................................. 63

Task 8: A Method Accepting Arguments and Returning Value .............................................................. 64

Task 9: A Method Accepting Arguments and Returning Value .............................................................. 65

Task 10: Exercise ....................................................................................................................................... 66

iv
Practical 1 : Introduction to Java™ Programming

Practical 1: Introduction
to Java™ Programming
(4 hours)
Learning Outcomes:

At the end of this lesson, students should be able to:


i. Create a new Java program,
ii. Type Java code,
iii. Save the Java file,
iv. Use output statements,
v. Construct Java™ program,
vi. Compile Java code, and
vii. Execute the Java program.

Task 1: Using Java editor (jGRASP)


STEP INSTRUCTIONS REMARKS
1 Create a new Java program.
Press keyboard key [Ctrl]+[N]
simultaneously.
2 Choose [Java], and
Click [OK].

Page 1
Practical 1 : Introduction to Java™ Programming

3 Type the following code:

class HelloWorld{
public static void main(String[] args){
System.out.print("Hello, world!");
}
}

4 Save the file.


Press keyboard key [Ctrl]+[S]
simultaneously.

5 At the [Look in:], choose your own


folder

6 In [File Name:], type the filename


exactly the same as class name.
For example: HelloWorld.java

Click the button [Save].


7 Compile the program. ----jGRASP exec: javac -g
Press keyboard key [Ctrl]+[B] HelloWorld.java
simultaneously.
----jGRASP: operation
complete.
8 Run the program. ----jGRASP exec: java
Press key [Ctrl]+[R] HelloWorld
simultaneously. Hello, world!
----jGRASP: operation
complete.
9 Verify the output.

Page 2
Practical 1 : Introduction to Java™ Programming

A Complete Java Program & Output

HelloWorld.java

class HelloWorld{

public static void main(String[] args){

System.out.print("Hello, world!");

Hello, world!

Java Source Code Explanation:

Code Explanation
class HelloWorld{ A class is required to write a Java
program.
}  class is a keyword for a Java
program.
 HelloWorld is any valid
identifiers to represent name of
the class.
 Open and close braces, { }
indicate the start and end of
the class.
A method main() is compulsory
in a Java class to:
public static void main(String[] args){  run the program, or
 call a method.
} Open and close braces, { }
indicate the start and end of the
method.
 System.out.print() is an
output statement to display
output on the console.
System.out.print("Hello, world!");
 "Hello, world!" is the
message to be displayed on the
console.

Page 3
Practical 1 : Introduction to Java™ Programming

Exercise 1:
Using the same file HelloWorld.java

1. Add an output statement that display a second message after the "Hello,
world!". Type something like, "I Like Computer Science." Compile
and run the program again.
2. Add another output statement that display a third message such as, "I
Learn Java." Compile and run the program again.
3. Add a comment to the program stating the author name and the purpose
of the program, recompile, and run it again. The new comment should not
affect the result. (*Hint: Use // or /* */)

Exercise 2:
1. Create a new Java program. ([Ctrl]+[N])
2. Type the following code:

class AboutMe{

public static void main(String[] args){

System.out.print("My name is Mohd.");


System.out.print("I am 18 years old.");
System.out.print("I study at Matriculation.");

}
}

3. Save the file as AboutMe.java. ([Ctrl]+[S])


4. Compile the program. ([Ctrl]+[B])
5. Run the program. ([Ctrl]+[R])
6. Verify the output.

Exercise 3:
Write a complete Java program to display the following output:

Java
Java Again
Still Java
Always Java
Java Forever...

Page 4
Practical 1 : Introduction to Java™ Programming

Task 2: Use Output Statement to Display Messages


1. Create a new Java program ([Ctrl]+[N]).
2. Type the following code:

class DisplayMessages{
public static void main(String[] args){

System.out.print("I Like Computer Science.");


System.out.print("I Love Programming.");
System.out.print("I Learn Java.");

}
}

3. Save the file as DisplayMessages.java in your preferred folder. ([Ctrl]+[S])


4. Compile and run the program. ([Ctrl]+[B])  ([Ctrl]+[R])
5. Verify the output.

I Like Computer Science.I Love Programming.I Learn Java.

In your opinion, why is the messages displayed in one consecutive line?

This is because, the output statement System.out.print will display the


output in one line.

So, how do we display the output messages in three (3) different lines?

There are two (2) options to do that:

Option 1. By replacing System.out.print with System.out.println, or


Option 2. Put the escape sequence \n that represent a new line, before
starting any new message.

Page 5
Practical 1 : Introduction to Java™ Programming

For example:

 Rename the Java file DisplayMessages.java to


DisplayMessages1.java and DisplayMessages2.java and modify the
source code as below:

DisplayMessages1.java

class DisplayMessages1{
public static void main(String[] args){

System.out.println("I Like Computer Science.");


System.out.println("I Love Programming.");
System.out.println("I Learn Java.");

}
}

OR

DisplayMessages2.java

class DisplayMessages2{
public static void main(String[] args){

System.out.print("\nI Like Computer Science.");


System.out.print("\nI Love Programming.");
System.out.print("\nI Learn Java.");

}
}

 Compile and run the code again.


 Verify the output. The output displayed should be like this:

I Like Computer Science.


I Love Programming.
I Learn Java.

*Note: Both files DisplayMessages1.java and DisplayMessages2.java will


produce the same output.

Page 6
Practical 1 : Introduction to Java™ Programming

Task 3: Displaying Formatted Output Using Escape Sequence


\n and \t
Suppose we want the output messages displayed as follows:

I Like Computer Science.


I Love Programming.
I Learn Java.

How do we do? Use the output statement, System.out.print().

1. Create a new Java program.


2. Type the following code:

class DisplayMessages3{
public static void main(String[] args){

System.out.print("\nI Like Computer Science.");


System.out.print("\n\tI Love Programming.");
System.out.print("\n\t\tI Learn Java.");

}
}

3. Save the file as DisplayMessages3.java


4. Compile and run the program.
5. Verify the output.

I Like Computer Science.


I Love Programming.
I Learn Java.

As you can see, the use of escape sequence \n and \t will display formatted
output as above.

Page 7
Practical 1 : Introduction to Java™ Programming

Task 4: Exercises
Write a complete Java program that will display the following output:

1. Output 1

Kolej Matrikulasi Kedah


Kementerian Pendidikan Malaysia
06010 Changloon, Kedah

2. Output 2

Kolej Matrikulasi Kedah


Kementerian Pendidikan Malaysia
06010 Changloon, Kedah

3. Output 3

My name is <your nickname>.


I am <age> years old.
I target <cgpa> for my final result.
Today date is <day> of <month>, <year>.

4. Output 4

0 2 4 6 8 is even numbers less than 10.


11 13 15 17 19 is odd numbers between 10 and 20.

5. Output 5

1 2 3 4 5 is positive integers less than 6.


-1 -2 -3 -4 -5 is negative integers greater than -6.

6. Output 6

#
# # #
# # # # #
# # #
#

Page 8
Practical 2 : Data Types, Operators, and Expressions

Practical 2: Data Types,


Operators, and
Expressions (4 hours)
Learning Outcomes:

At the end of this lesson, students should be able to:


i. Use primitive data types in a program,
ii. Use arithmetic operators,
iii. Use relational operators,
iv. Use logical operators, and
v. Construct simple programs using primitive data types, operators and
expressions.

Task 1: Displaying Values of Variables


Create a complete Java program that will display the contents of variables such
as name, age, weight, marital status, and gender. Save, compile, and run the
program. Verify the output.

class DisplayVariablesValue{
public static void main(String[] args){
String name="Maziyana";
int age=18;
double weight=65.4;
boolean married=true;
char gender='F';

System.out.println("Name: "+ name);


System.out.println("Age: "+ age);
System.out.println("Weight: "+ weight);
System.out.println("Married? "+ married);
System.out.println("Gender: "+ gender);
}
}
Name: Maziyana
Age: 18
Weight: 65.4
Married? true
Gender: F

Page 9
Practical 2 : Data Types, Operators, and Expressions

Concept of Variables

Code Description

A variable named name is declared as data type


String name="Maziyana";
String and store the value “Maziyana”.

A variable named age is declared as data type


int age=18;
integer, int and store the value 18.

A variable named weight is declared as data


double weight=65.4;
type double and store the value 65.4.

A variable named married is declared as data


boolean married=true;
type boolean and store the value true.

A variable named gender is declared as data


char gender='F';
type character, char and store the value ‘F’.

Variable’s value “Maziyana” 18 65.4 true ‘F’

Variable’s name name age weight married gender

The output statements

System.out.println("Name: "+ name);


System.out.println("Age: "+ age);
System.out.println("Weight: "+ weight);
System.out.println("Married? "+ married);
System.out.println("Gender: "+ gender);

will display the values stored in the variables on the console.

Name: Maziyana
Age: 18
Weight: 65.4
Married? true
Gender: F

Page 10
Practical 2 : Data Types, Operators, and Expressions

Task 2: Displaying Values of Variables Entered by User


Create a complete Java program (DisplayEnteredVariables.java) that will enable
user to enter name, age, height, marital status, and favorite character, then
display the values of the variables. Save, compile, and run the program. Verify
the output.

Import java.util.Scanner;
class DisplayEnteredVariables{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);

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


String name=sc.next();
System.out.print("Enter age: ");
int age=sc.nextInt();
System.out.print("Enter height: ");
double height=sc.nextDouble();
System.out.print("Enter marital status: ");
boolean married=sc.nextBoolean();
System.out.print("Enter favorite letter: ");
char letter=sc.next().charAt(0);

System.out.println("Name: "+ name);


System.out.println("Age: "+ age);
System.out.println("Height: "+ height);
System.out.println("Married? "+ married);
System.out.println("Fav. Letter: "+ letter);
}
}
Enter name: Izliah
Enter age: 63
Enter height: 1.86
Enter marital status: false
Enter favorite letter: A
Name: Izliah
Age: 18
Height: 1.86
Married? false
Fav. Letter: A

Complete the following concept:

Variable’s value 18 false ‘A’

Variable’s name name P Q R S

Page 11
Practical 2 : Data Types, Operators, and Expressions

Task 3: Arithmetic Calculations


Create a complete Java program (ArithmeticMain.java) that will calculate and
display all the arithmetic result from two integers entered by user.

import java.util.Scanner; A Scanner class which is define


in java.util package
class ArithmeticMain{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);

System.out.print("Enter two numbers: "); create an object (sc)


int num1=sc.nextInt(); of a Scanner class
int num2=sc.nextInt();

int add = num1 + num2; read input from the


int sub = num1 - num2; keyboard, and assign the
int mul = num1 * num2;
value to a variable name
int div = num1 / num2;
int mod = num1 % num2; num1.

System.out.println("Addition: "+ add);


System.out.println("Subtraction: "+ sub);
System.out.println("Multiplication: "+ mul);
System.out.println("Division: "+ div);
System.out.println("Modulus: "+ mod);
}
}

Enter two numbers: 9 3


Addition: 12
Subtraction: 6
Multiplication: 27
Division: 3
Modulus: 0

*Note: What is meant by “entered by user”?

In Java program, “entered by user”means to read input from the keyboard, which
allows user to enter some input and it will be parsed into a primitive data types
such as int, double, boolean, or char.

To do this, we create an object of a Scanner class which is define in import


java.util.scanner package.

Page 12
Practical 2 : Data Types, Operators, and Expressions

Task 4: Using Relational Operators


Create a complete Java program (MarksApp.java) that will calculate and display
the average of three marks entered by user, then determine the status “PASS” or
“FAIL”. (Passing marks is 40)

import java.util.Scanner; Import class Scanner

class MarksApp{
public static void main(String[] args){
Scanner sc = new Scanner(System.in); Create object, sc

System.out.print("Enter three marks: ");


double mark1=sc.nextDouble(); Read input from keyboard,
double mark2=sc.nextDouble(); and assign the decimal
double mark3=sc.nextDouble();
values to the variables
mark1, mark2, and mark3.
double avg = (mark1+mark2+mark3)/3;
System.out.println("Average is "+ avg);

if(avg > 40)


System.out.println("\nPASS");
else
System.out.println("\nFAIL");
}
}

Enter three marks: 97.5 75.3 46.8


Average is 73.2
PASS

*Note:

Relational and logical operators are mainly used as expressions in:

 selection control structures using if() statement, and


 repetition control structures using while() or for() statements.

The result from the evaluation of relational and logical expressions would be in
form of Boolean value only i.e: true or false .

Page 13
Practical 2 : Data Types, Operators, and Expressions

Task 5: Using Relational and Logical Operators


Create a complete Java program (MarksGrade.java) that will determine the grade
for the marks entered by user based on the following table:

Marks Range Grade


80 – 100 A
60 – 79.9 B
50 – 59.9 C
40 – 49.9 D
0 – 39.9 F

import java.util.Scanner;
class MarksGrade{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
char grade='Z';

System.out.print("Enter a mark (0 - 100): ");


double mark=sc.nextDouble();

if(mark>=80 && mark<=100)


grade = 'A';
else if(mark>=60 && mark<80)
grade = 'B';
else if(mark>=50 && mark<60)
grade = 'C';
else if(mark>=40 && mark<50)
grade = 'D';
else if(mark>=0 && mark<40)
grade = 'F';
else
System.out.println("Mark not in range.");

System.out.println("Grade: "+ grade);


}
}
Enter a mark (0 - 100): 97.5
Grade: A

Page 14
Practical 2 : Data Types, Operators, and Expressions

Task 6: Exercise
1 Create a complete Java program that will display the contents of variables
such as favorite color, favorite number, height, employment status
(employed/unemployed), and favorite character. Save, compile, and run
the program. Verify the output.

2 Create a complete Java program that will enable user to enter favorite
color, favorite number, height, employment status
(employed/unemployed), and favorite character, then display the values
of the variables. Save, compile, and run the program. Verify the output.

3 Create a complete Java program that will calculate and display perimeter,
surface area, and volume of a cuboid. The value for length, width, and
height will be entered by user.

4 Create a complete Java program that will calculate and display the total
and average of seven marks entered by user, then determine the status
“PASS” or “FAIL”. (Passing marks is 40)

5 Create a complete Java program that will determine the CGPA for the
grade entered by user based on the following table:

CGPA Grade
4.00 A
3.67 A-
3.33 B+
3.00 B
2.67 B-
2.33 C+
2.00 C
1.67 C-
1.33 D
1.00 E
0.00 F

6 Write a complete Java program that will read and display your nickame,
age, gender, weight, and height.

7 Write a complete Java program that will calculate and display your BMI
based on your weight and height. Then give the status of your BMI.

Page 15
Practical 3 : Sequence Control Structure

Practical 3: Sequence
Control Structure
(2 hours)
Learning Outcomes:

At the end of this lesson, students should be able to:


i. Construct program using sequence control structures.

Task 1: Find the square of a number entered by user


Problem Statement
Find the square of a number entered by user.

Pseudocode Java segment code


Start {
Read number number = sc.nextInt();
square = number2 square = number*number;
Display square System.out.print(square);
End }

Type the following code, then save, compile, and run the code. Verify the output.

Square.java
import java.util.Scanner;
class Square{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int number, square;

number = sc.nextInt();
square = number*number;
System.out.print(square);
}
}
9
81

Page 16
Practical 3 : Sequence Control Structure

Task 2: Calculate and display the average of three marks


Problem Statement
Find the square of a number entered by user.

Pseudocode Java segment code


Start {
Read mark1, mark2, mark3 m1 = sc.nextDouble();
average = (mark1+ mark 2+ mark 3)/3 m2 = sc.nextDouble();
Print average m3 = sc.nextDouble();
End avg = (m1+m2+m3)/3;
System.out.print(avg);
}

Type the following code, then save, compile, and run the code. Verify the output.

Average.java
import java.util.Scanner;

class Average{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
double m1,m2,m3,avg;

m1 = sc.nextDouble();
m2 = sc.nextDouble();
m3 = sc.nextDouble();
avg = (m1+m2+m3)/3;
System.out.print(avg);
}
}

98
76
54
76.0

Page 17
Practical 3 : Sequence Control Structure

Task 3: Calculate and display the area of a rectangle


Problem Statement
Calculate and display the area of a rectangle.

Pseudocode Java segment code


Start {
Get length, width l = sc.nextDouble();
area = length x width w = sc.nextDouble();
Print area area = l*w;
End System.out.print(area);
}

Type the following code, then save, compile, and run the code. Verify the output.

RectangleArea.java

import java.util.Scanner;

class RectangleArea{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
double l,w,area;

l = sc.nextDouble();
w = sc.nextDouble();
area = l*w;
System.out.print(area);
}
}

7
9
63.0

Page 18
Practical 3 : Sequence Control Structure

Task 4: Swapping values of two variables


Problem Statement
Swapping values of two variables.

Pseudocode Java segment code


Start {
Get value1, value2 int val1=77, val2=99;
temp = value1 tmp = val1;
value1 = value2 val1 = val2;
value2 = temp val2 = tmp;
Print value1, value2 System.out.println("First value AFTER swap: "+ val1);
System.out.println("Second value AFTER swap: "+ val2);
End
}

Type the following code, then save, compile, and run the code. Verify the output.

SwapValue.java

class SwapValue{
public static void main(String[] args){
int val1=77, val2=99, tmp;

System.out.println("First value BEFORE swap: "+ val1);


System.out.println("Second value BEFORE swap: "+ val2);
tmp = val1;
val1 = val2;
val2 = tmp;
System.out.println("First value AFTER swap: "+ val1);
System.out.println("Second value AFTER swap: "+ val2);
}
}

First value BEFORE swap: 77


Second value BEFORE swap: 99
First value AFTER swap: 99
Second value AFTER swap: 77

*Note: In the above program, value for variable val1 and val2 is initialized by
the system.

Page 19
Practical 3 : Sequence Control Structure

Task 5: Adding two numbers


Problem Statement
Adding two numbers which values are initialized by the system.

Type the following code, then save, compile, and run the code. Verify the output.

AddNumbers.java
class AddNumbers{

public static void main(String[] args){

int num1=3, num2=9, add=0;

add = num1 + num2;

System.out.print("Total: "+ add);


}
}
Total: 12

Explanation:
In this problem statement, the value for the variables num1, num2, and add is
declared and initialized by the system, i.e:

int num1=3, num2=9, add=0;

means, the variables num1, num2 and add are declared as integer data type (int)
and initialized with values 3, 9, and 0 respectively.

The expression

add = num1 + num2;

means, the result from the addition of the variables num1 and num2 is assigned to
the variable named add.

Page 20
Practical 3 : Sequence Control Structure

The output statement

System.out.print("Total: "+ add);

will display output, Total: , concatenate (+) with the value stored in the variable
add.

3 9 12

num1 num2 add

Computer Memory

Page 21
Practical 3 : Sequence Control Structure

Task 6: Difference between two numbers


Problem Statement
Create a complete Java program name SubtractNumbers.java that will accept two
numbers from user and find the difference between numbers entered.

Type the following code, then save, compile, and run the code. Verify the output.

SubtractNumbers.java
import java.util.Scanner;
class SubtractNumbers{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int num1=0,num2=0,result=0;

System.out.print("Enter first number: ");


num1=sc.nextInt();

System.out.print("Enter second number: ");


num2=sc.nextInt();

result=num1-num2;

System.out.print("Difference: "+ result);


}
}
Enter first number: 3
Enter second number: 9
Difference: -6

Explanation:
In this Java program (SubtractNumbers.java), the value for the variables (num1
and num2) is entered by user through the keyboard. Hence, we need to import the
class Scanner from package java.util using the statement

import java.util.Scanner;

Then, the object sc will be created using class Scanner,

Scanner sc=new Scanner(System.in);

Next, the statement

System.out.print("Enter first number: ");

is a user-friendly feature that will prompt user to Enter first number:

Page 22
Practical 3 : Sequence Control Structure

Next, the statement

num1=sc.nextInt();

will read next integer input from user and assign it to the variable num1. Assume
user enter value 3.

num1

The statements

System.out.print("Enter second number: ");

num2=sc.nextInt();

will prompt user to Enter second number: , and

read the next integer input and assign it to the variable num2. Assume user enter
value 9.

num2

Next, the statement

result=num1-num2;

Suppose the user entered 3 for first input, and 9 for second input, the variable
result will store the value from the subtraction between 3 and 9 i.e -6. So the
value -6 will be stored in the variable result.

-6

result

The statement

System.out.print("Difference: "+ result);

will display the output as Difference: -6.

3 9 -6
num1 num2 result

Computer Memory

Page 23
Practical 3 : Sequence Control Structure

Task 7: Calculate and display the average of three (3) marks


entered by user.
Problem Statement
Create a complete Java program (StudentMark.java) that will calculate and
display the total and average of three (3) marks entered by user.

StudentMark.java
import java.util.Scanner;

class StudentMark{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);

int mark1=0, mark2=0, mark3=0;


double total=0, average=0;

System.out.print("Enter mark 1: ");


mark1 = sc.nextInt();
System.out.print("Enter mark 2: ");
mark2 = sc.nextInt();
System.out.print("Enter mark 3: ");
mark3 = sc.nextInt();

total = mark1+mark2+mark3;
average = (mark1+mark2+mark3)/3;

System.out.println("Total marks:"+ total);


System.out.println("Average marks:"+ average);
}
}
Enter mark 1: 90
Enter mark 2: 89
Enter mark 3: 79
Average marks:258.0
Average marks:86.0

*Note: Remember to name the Java file created, same as the class name.

Page 24
Practical 3 : Sequence Control Structure

Task 8: Exercise
Instruction: Write a complete Java program to solve the following problems.

1 The Computer Science lecturers wish to determine the final mark for every
student. The final marks are taken from average marks of two (2) quizzes
and total of two (2) tests. Print the final marks for a student.

2 A factory worker is paid based on the total working hours of RM 5.50 per
hour. 11% of the total salary will be deducted for contribution to KWSP.
Prepare the monthly net salary of the factory worker.

3 Convert the weight from kilogram to pound. (Formula: Weight in pound =


weight in kilogram x 2.2)

4 A car travels from station A to station B. Calculate the distance from


station A to station B. (distance = speed x time)

5 Calculate the sale price of a book after given a 35% discount.

6 Calculate and display four mathematical calculations; addition,


multiplication, subtraction and division for two numbers.

7 Given the Splash Water Park entrance ticket rates as shown below:

Ticket price for adult : RM 13.50


Ticket price for children : RM 7.90

Create a program that allows a user to key in the number of family


members based on the criteria above, and then calculate the total ticket
price for a family.

8 Prime College offers two courses; Robotic course and Networking course.
The current fee for the Robotic course is RM55 per month and for the
Networking is RM105 per month. Students can register for only one of the
course or for both courses. Help the manager to calculate the total fees
paid by all students for each course, and then calculate the total fees for
both courses.

9 Madam Hasni takes a car loan at a bank. The interest rate fixed by the
bank is 4% per year, which means she has to pay the interest of 4% of the
loan every year. She is allowed to pay the total of her loan plus the interest
by monthly installment. Calculate the total amount that she has to pay to
the bank and the monthly payment that she has to make.

Page 25
Practical 4 : Selection Control Structure

Practical 4: Selection
Control Structure
(2 hours)
Learning Outcomes:

At the end of this lesson, students should be able to:


i. Construct program using selection control structures.

Task 1: Single Selection using if statement


Problem Statement
Print the message “You are entitle to vote.” for a person whose age is above 20.

Pseudocode Java segment code


Start {
Read age age = sc.nextInt();
If age > 20 if(age>20)
Print message “You are entitle to vote.” System.out.print("You are entitle to
endif vote.");
End }

Type the following code, then save, compile, and run the code. Verify the output.

Vote.java
import java.util.Scanner;
class Vote{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int age;

age = sc.nextInt();
if(age>20)
System.out.print("You are entitle to vote.");
}
}
21
You are entitle to vote.

Page 26
Practical 4 : Selection Control Structure

Task 2: Single Selection using if statement


Problem Statement
Write a complete Java program that will determine the “PASS” status of a
student based on mark keyed in by user. (Passing mark is 40)

Pass.java

import java.util.Scanner;

class Pass{

public static void main(String[] args){

Scanner sc = new Scanner(System.in);

int mark=0;

mark=sc.nextInt();

if(mark>=40)
System.out.print("PASS");
}
}

97
PASS

Page 27
Practical 4 : Selection Control Structure

Task 3: Exercise
Instruction: Write a complete Java program to solve the following problems.

1 If a student is in Modul 2 group, display the message “The student is


taking Computer Science subject”.

2 Create a program that will accept student’s name and age. If the student’s
age is below 45, the program will print a message “You are eligible to take
a PhD programme”.

3 Print the message “You’re entitle to vote” for a person whose age is above
20.

4 Display a message “You are an excellent student” for a student whose


cumulative grade point average (CGPA) is 3.75 or above.

5 Determine whether a number entered by a user is an even number. (Hint:


use modulus operator %)

6 If a person is a minor (under 21 years of age), print the message “Youth is


a wonderful thing. Enjoy it!”. Display a message “Age is a state of mind”
regardless of any age entered.

Page 28
Practical 4 : Selection Control Structure

Task 4: Dual Selection using if/else statement


Problem Statement
Find if a number is odd or even. If the number is odd then display message “Odd
number”, otherwise, display message “Even number”.

Pseudocode Java segment code


Start {
Read number num = sc.nextInt();
If number is divisible by 2 if(num%2!=0)
Print message “Even number.” System.out.print("Odd number.");
Else else
Print message “Odd number.” System.out.print("Even number.");
endif
End }

Type the following code, then save, compile, and run the code. Verify the output.

OddEven.java

import java.util.Scanner;

class Oddven{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int num;

num = sc.nextInt();
if(num%2!=0)
System.out.print("Odd number.");
else
System.out.print("Even number.");
}
}

7
Odd number.

Page 29
Practical 4 : Selection Control Structure

Task 5: Dual Selection using if/else statement


Problem Statement
Compare two integer variables and display either message “num1 is greater than
num2”or message “num2 is greater than num1”.

Pseudocode Java segment code


Start {
Read num1, num2 num1 = sc.nextInt();
If num1 > num2 num2 = sc.nextInt();
Print message “num1 is greater than if(num1>num2)
num2” System.out.print("num1 is greater
Else than num2.");
Print message “num2 is greater than else
num1” System.out.print("num2 is greater
Endif than num1.");
End }

Type the following code, then save, compile, and run the code. Verify the output.

Greater.java

import java.util.Scanner;

class Greater{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int num1,num2;

num1 = sc.nextInt();
num2 = sc.nextInt();
if(num1>num2)
System.out.print("num1 is greater than num2.");
else
System.out.print("num2 is greater than num1.");
}
}

7 4
num1 is greater than num2.

Page 30
Practical 4 : Selection Control Structure

Task 6: Dual Selection using if/else statement


Problem Statement
Determine whether a year is a leap year or not a leap year.

Pseudocode Java segment code


Start {
Read year year = sc.nextInt();
If year%4=0 and year%100 != 0 and
year%400=0 if(((year%4==0)&&(year%100!=0)&&(y
Print message “leap year” ear%400==0))
Else System.out.print("Leap
Print message “not leap year” year.");
endif else
End System.out.print("Not Leap
year.");

Type the following code, then save, compile, and run the code. Verify the output.

LeapYear.java

import java.util.Scanner;

class LeapYear{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int year;

year = sc.nextInt();
if((year%4==0)&&(year%100!=0)&&(year%400==0))
System.out.print("Leap year.");
else
System.out.print("Not leap year.");
}
}

1977
Not leap year.

Page 31
Practical 4 : Selection Control Structure

Task 7: Dual Selection using if/else statement


Write a complete Java program that will determine the “PASS” or “FAIL” status
of a student based on mark entered by user. (Passing mark is 40)

PassFail.java

import java.util.Scanner;

class PassFail{

public static void main(String[] args){

Scanner sc = new Scanner(System.in);

double mark=0;

mark=sc.nextDouble();

if(mark>=40)
System.out.print("PASS");
else
System.out.print("FAIL");
}
}

39.9
FAIL

Page 32
Practical 4 : Selection Control Structure

Task 8: Exercise
Instruction: Write a complete Java program to solve the following problems.

1 If a student is in Modul 2 group, display the message “The student is


taking Computer Science subject”. Otherwise, display the message “The
student is taking Biology subject”.

2 Determine whether a number entered by a user is an even or odd number.


(Hint: use modulus operator %)

3 MyHealth magazine is sold at RM5 each if at least 5 units of the magazine


are purchased, and it is sold at the price of RM7 each otherwise. Calculate
the price a customer has to pay after he enters the quantity of the
magazines that he purchased.

4 A program will asks user to enter age for two peoples, where the values
entered will be stored in variables age1 and age2. Display “The first
person is older” when age1 is greater than age2, else display “The second
person is older”.

5 Calculate BMI when a user enters weight and height. Print “Please reduce
your weight” if BMI is greater and equal to 25.0. If not, print “You have an
ideal weight”.

6 A customer who rents a car will be charged RM60 if he rents for only 24
hours or less. Otherwise, RM5 per hour will be charged for additional
hours. Calculate and display the charge of a car rental.

7 An allowance for a part time lecturer will be paid monthly based on the
total lecture hours per month. Payment rate is as follows:

First 12 hours - RM 100 per hour


Additional hours - RM 50 per hour

Calculate the monthly allowance for a part time lecturer.

8 Calculate electric bill based on the electricity usage in watt as given below:

Usage less than or equal to 1000 - charge is 20 cents per


watt.
Additional usage more than 1000 - charge is 10 cents per
watt.

Page 33
Practical 4 : Selection Control Structure

Task 9: Multiple Selection using if else/if statement


Problem Statement
Check whether a number is positive, negative, or zero.

Pseudocode Java segment code


Start {
Read num num = sc.nextInt();
If num > 0 if(num<0)
Print message “Positive number” System.out.print("Negative.");
else if num < 0 else if(num>0)
Print message “Negative number” System.out.print("Positive.");
else else
Print message “Zero number” System.out.print("Zero.");
endif
End }

Type the following code, then save, compile, and run the code. Verify the output.

PosNegZero.java

import java.util.Scanner;

class PosNegZero{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int num;

num = sc.nextInt();
if(num<0)
System.out.print("Negative.");
else if(num>0)
System.out.print("Positive.");
else
System.out.print("Zero.");
}
}

77
Positive.

Page 34
Practical 4 : Selection Control Structure

Task 10: Multiple Selection using if else/if statement


Problem Statement
Determine the largest number among three numbers entered by user.

Pseudocode Java segment code


Start {
Read a,b,c a = sc.nextInt();
If a>b and a>c b = sc.nextInt();
Largest = a c = sc.nextInt();
else if b>a and b>c if(a>b&&a>c)
Largest = b largest=a;
Else if c>a and c>b else if(b>a&&b>c)
Largest = c largest=b;
Endif else if(c>a&&c>b)
Print Largest largest=c;
End System.out.print("Largest: "+
largest);
}

Type the following code, then save, compile, and run the code. Verify the output.

PosNegZero.java

import java.util.Scanner;

class PosNegZero{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int a,b,c, largest=0;

a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
if(a>b&&a>c)
largest=a;
else if(b>a&&b>c)
largest=b;
else if(c>a&&c>b)
largest=c;
System.out.print("Largest: "+ largest);
}
}

3 1 2
Largest: 3

Page 35
Practical 4 : Selection Control Structure

Task 11: Multiple Selection using if else if statement


Problem Statement
Write a complete Java program that will print the grade of a student based on
mark entered by user. The student’s grade determined according to the following
table:

Marks Grade
Greater than or equal to 80 A
Greater than or equal to 70 B
Greater than or equal to 50 C
Greater than or equal to 40 D
Less than 40 F

StudentGrade.java

import java.util.Scanner;

class StudentGrade{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
double mark=0;
char grade;

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


mark=sc.nextDouble();

if(mark>=80)
grade = 'A';
else if(mark>=70)
grade = 'B';
else if(mark>=50)
grade = 'C';
else if(mark>=40)
grade = 'D';
else
grade = 'F';
System.out.print("Grade: "+ grade);
}
}

Enter mark: 97.5


Grade: A

Page 36
Practical 4 : Selection Control Structure

Task 12: Exercise


Instruction: Write a complete Java program to solve the following problems.

1 Create a program that will ask a user to enter age for two people. Display
“The first person is older” when age1 is greater than age2, else display
“The second person is older”. If both are not true, display “Both person
are same age”.

2 Calculate and display Body Mass Index (BMI) based on weight in


kilograms and height in meters entered by user. Then display the
appropriate message based on the following table:

Weight Categories BMI (kg/m2)


Underweight < 18.5
Healthyweight 18.5 – 24.9
Overweight 25 – 29.9
Obese 30 – 34.9
Severely Obese 35 – 39.9
Morbidly Obese >= 40

3 Calculate water bill based on water consumption as given below:

Usage less than 20 m3 - charge is 43 sen per m3


Usage between 20 m3 to 40 m3 - charge is 21 sen per m3
More than 40 m3 - charge is 13 sen per m3

4 Calculate phone bill based on the following term:

Usage less than RM50 per month - no discount will be given


Usage less than RM100 per month - get 7% discount
Usage more than RM100 per month - get 21% discount

Page 37
Practical 5 : Repetition Control Structure (Sentinel-controlled)

Practical 5: Repetition
Control Structure
(2 hours)
Learning Outcomes:

At the end of this lesson, students should be able to:


i. Construct program using repetition control structures.

Task 1: Repetition using while statement


Problem Statement
Write a complete Java program that will print message “I Love Computer
Science” 7 times.

DisplayMessage.java

class DisplayMessage{
public static void main(String[] args){

int counter=0;

while(counter<7){
System.out.println("I Love Computer Science");
counter=counter+1;
}
}
}

I Love Computer Science


I Love Computer Science
I Love Computer Science
I Love Computer Science
I Love Computer Science
I Love Computer Science
I Love Computer Science

Page 38
Practical 5 : Repetition Control Structure (Sentinel-controlled)

Task 2: Repetition using while statement


Problem Statement
Write a complete Java program that will print first 10 integers.

DisplayCounter.java
class DisplayCounter{

public static void main(String[] args){

int counter=1;

while(counter<=10){
System.out.print(counter);
counter=counter+1;
}

}
}
12345678910

Task 3: Repetition using while statement


Problem Statement
Write a complete Java program that will calculate and display the sum of 7
numbers entered by user.

Sum.java
import java.util.Scanner;
class Sum{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int counter=0, sum=0;
while(counter<7){
System.out.print("Enter a number: ");
sum = sum + sc.nextInt();
counter=counter+1;
}
System.out.print("Sum: "+ sum);
}
}
Enter a number: 12
Enter a number: 34
Enter a number: 56
Enter a number: 78
Enter a number: 90
Enter a number: 98
Enter a number: 87
Sum: 455

Page 39
Practical 5 : Repetition Control Structure (Sentinel-controlled)

Task 4: Repetition using while statement


Problem Statement
Write a complete Java program that will accept 10 numbers entered by user. Then
find the sum for each odd and even numbers.

Sum.java

import java.util.Scanner;

class SumOddEven{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);

double counter=0, num=0, even=0, odd=0;

while(counter<10){
System.out.print("Enter a number: ");
num = sc.nextDouble();

if(num%2==0)
even = even+num;
else
odd = odd+num;
counter=counter+1;
}

System.out.print("\nSum of odd number: "+ odd);


System.out.print("\nSum of even number: "+ even);
}
}

Enter a number: 97.5


Enter a number: 100
Enter a number: 88.5
Enter a number: 64.5
Enter a number: 36.5
Enter a number: 99
Enter a number: 100
Enter a number: 86
Enter a number: 48
Enter a number: 72

Sum of odd number: 386.0


Sum of even number: 406.0

Page 40
Practical 5 : Repetition Control Structure (Sentinel-controlled)

Task 5: Repetition using for statement


Write a complete Java program that will accept 10 numbers entered by user. Then
find the sum for each odd and even numbers.

SumOddEven.java

import java.util.Scanner;

class SumOddEven{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
double num=0, even=0, odd=0;
for(int counter=0;counter<10;counter++){
System.out.print("Enter a number: ");
num = sc.nextDouble();
if(num%2==0)
even = even+num;
else
odd = odd+num;
}
System.out.print("\nSum of odd number: "+ odd);
System.out.print("\nSum of even number: "+ even);
}
}

Enter a number: 97.5


Enter a number: 100
Enter a number: 88.5
Enter a number: 64.5
Enter a number: 36.5
Enter a number: 99
Enter a number: 100
Enter a number: 86
Enter a number: 48
Enter a number: 72

Sum of odd number: 386.0


Sum of even number: 406.0

Page 41
Practical 5 : Repetition Control Structure (Sentinel-controlled)

*Note: You will get the same output similar to a while statement, even though
you are using a for loop. Why?

This is because, the for loop does not change the logic of the program but the
difference is the syntax used in the program.

while statement for statement

int counter = 0;
for(int counter = 0;counter<limit;
while(counter < limit){ counter++){

System.out.print(“Test”); System.out.print(“Test”);

counter = counter+1; }

*Note:

 You can see that the loop-control-variable (counter) is exists in different


location, but the logic of execution still the same.
 The execution of expression counter = counter + 1; is similar and
equal to counter++;

Page 42
Practical 5 : Repetition Control Structure (Sentinel-controlled)

Task 6: Exercise
Instruction: Write a complete Java program for each of the problems.

1 Print “I love computer Science” 20 times.

2 Print any 10 numbers entered by user.

3 Calculate and display the sum of 10 numbers entered by user.

4 Calculate and display the average of 10 numbers entered by user.

5 Print the first 10 positive integers.

6 Print the first 10 positive even numbers.

7 Print odd numbers from 3 to 39.

8 Print multiples of 5 which are less than 30.

9 Print the squares of 10 numbers entered by user.

10 Calculate and display the total for the first 20 positive integers.

11 Calculate and display the average for the first 30 positive integers.

12 Calculate the sum of all even numbers from 2 to 100.

13 Calculate the area of 10 rectangles.

14 Find the average marks for 10 tests that have been taken by a student.

15 Calculate and print the average of three tests for 30 students.

16 A program will determine the total and average price for a few items. The
number of items will be entered by user at the start of the program.

17 Given a list of daily temperatures for a certain number of days, design an


algorithm to calculate the total temperature. The first input is the number
of days.

18 A program will determine the total and average price for a few items
bought by a user. The number of items will be entered by user at the start
of the program.

Page 43
Practical 5 : Repetition Control Structure (Sentinel-controlled)

Task 7: Repetition using sentinel-controlled


Write a Java program that will accept marks from user and find the highest mark
entered. The process will continue until user keyed in -1.

Pseudocode
Start
Read mark
Set mark as highest
While mark not equal to sentinel value
Read mark
If mark > highest
Set mark as highest
Endwhile
Print highest
End

HighestMark.java
import java.util.Scanner;
class HighestMark{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
double mark=0, highest;

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


mark = sc.nextDouble();
highest = mark;

while(mark != -1){
System.out.print("Enter mark: ");
mark = sc.nextDouble();
if(mark>highest)
highest = mark;
}
System.out.print("Highest: "+ highest);
}
}
Enter mark: 87.6
Enter mark: 43.2
Enter mark: 90.2
Enter mark: 54.6
Enter mark: 98
Enter mark: 34.7
Enter mark: 23.5
Enter mark: -1
Highest: 98.0

Page 44
Practical 5 : Repetition Control Structure (Sentinel-controlled)

Task 8: Exercise
Instruction: Write a complete Java program for each of the problems.

1 A program that will accepts a list of product price from user and calculate
the total price. The process will continue until the user enters value -1.

2 Calculate the total temperature for a list of daily temperatures that will be
entered by user. The calculation will stop when the value of temperature
entered is -999.

3 A program will calculate the average for a few integers entered by user.
The user should key in 0 to terminate the sequence.

4 Calculate the average of a few students’ height. The value -1 for height
indicates the end of input.

5 A program will accept a series of numbers from user and determine


whether each number entered is an even or odd number. The program
will stop when a user enters 0.

6 Write a Java program that will accept marks from user and calculate the
total marks. The process will continue until the user enters -1.

7 A program will print first ten multiplication value based on number


entered by user.

Page 45
Practical 6 : Arrays

Practical 6: Arrays
(6 hours)
Learning Outcomes:

At the end of this lesson, students should be able to:


i. Construct programs that perform one-dimensional array operations for
problems involving frequency and total.

Task 1: Declare and Enter Data into Arrays

Problem Statement
Create a Java program that contain two lists containing names and ages for seven
(7) persons. The data will be entered by user. Then display the lists.

import java.util.Scanner;
class ArrayMain{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String[] name = new String[7];
int[] age = new int[7];

for(int i=0;i<name.length;i++){
System.out.print("Enter name and marks: ");
name[i] = sc.next();
age[i] = sc.nextInt();
}

for(int i=0;i<name.length;i++){
System.out.println("Name: "+ name[i] +", age: "+ age[i]);
}
}
}
Enter name and marks: Adam 930
Enter name and marks: Nuh 1000
Enter name and marks: Ibrahim 195
Enter name and marks: Ismail 137
Enter name and marks: Ishak 137
Enter name and marks: Yaakob 144
Enter name and marks: Muhammad 63
Name: Adam, age: 930
Name: Nuh, age: 1000
Name: Ibrahim, age: 195

Page 46
Practical 6 : Arrays

Name: Ismail, age: 137


Name: Ishak, age: 137
Name: Yaakob, age: 144
Name: Muhammad, age: 63

Explanation:
Code Explanation

Declare and create String array


String[] name = new String[7];
named name sized 7.

Declare and create int array named


int[] age = new int[7];
age sized 7.

for(int i=0;i<name.length;i++){ The statements in loop-body will


//loop-body repeat name.length times i.e: 7 times.
} name.length is the size of the array.

System.out.print("Enter name and Prompt user to Enter name and


marks: "); marks:

The element[i] of the array name will


name[i] = sc.next();
store String value entered by user.

The element[i] of the array age will


age[i] = sc.nextInt();
store int value entered by user.

The statements in loop-body will


for(int i=0;i<name.length;i++){
execute name.length times i.e: 7
//loop-body
times.
}
name.length is the size of the array.

System.out.println("Name: "+ will display output name and age, and


name[i] +", age: "+ age[i]); move to new line.

Page 47
Practical 6 : Arrays

Task 2: Accessing Elements in an Array


Given a lists of names and ages. Find the eldest among them.

import java.util.Scanner;

class ArrayMain{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String[] name = {"Sulaiman", "Daud", "Musa", "Yusof",
"Muhammad"};
int[] age = {180, 70, 123, 110, 63};

int oldest = age[0];


String nameold = name[0];
//accessing elements in an array
for(int i=1;i<name.length;i++){
if(age[i]>oldest){
oldest = age[i];
nameold = name[i];
}
}
System.out.print("The eldest is: "+ nameold +", "+ oldest);
}
}

The eldest is: Sulaiman, 180

Explanation:
Code Explanation

String[] name = {"Sulaiman", Declare String array named name and


"Daud", "Musa", "Yusof", initialize String values to the array
"Muhammad"}; name.

Declare int array named age and


int[] age = {180, 70, 123, 110,
initialize integer values to the array
63};
age.
Set the first element of array age to
int oldest = age[0];
the variable oldest.
if(age[i]>oldest){
Compare the element age[i] to
oldest = age[i];
oldest.
nameold = name[i];
If true then update oldest.
}

Page 48
Practical 6 : Arrays

Task 3: Displaying Elements in an Array


Write a complete Java program which create a double array marks, containing
the following values:

97.5 75.3 53.1 86.4 64.2

13.5 35.7 57.9 24.6 46.8

Then display all the elements in the array and sum of the elements in the array.

PrintArray.java
class PrintArray{
public static void main(String[] args){
double[] marks =
{97.5,75.3,53.1,86.4,64.2,13.5,35.7,57.9,24.6,46.8};
double sum=0;

for(int i=0;i<marks.length;i++){
System.out.print(marks[i] +"\t");
sum=sum+marks[i];
}
System.out.print("\nSum: "+ sum);
}
}
97.5 75.3 53.1 86.4 64.2 13.5 35.7 57.9 24.6 46.8
Sum: 555.0

Task 4: Linear Search


Linear search or sequential search is a process for finding a target value within a
list.

It sequentially checks each element of the list for the target value until a match is
found or until all the elements have been searched.

class LinearSearch{
public static void main(String[] args){
int search=30, array[]={10,20,30,40,50,60,70};

for(int i=0; i<array.length; i++){


if(search == array[i])
System.out.println(search + " is present "
+"at index " + i);
}
}
}

30 is present at index 2

Page 49
Practical 6 : Arrays

Task 5: Find Average


Write a complete Java program which accept ten (10) marks from user and store
it in the array marks, then display all elements in the array and the average of
the elements in the array.

PrintArray2.java

import java.util.Scanner;

class PrintArray2{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
double[] marks = new double[10];
double sum=0, avg=0;

for(int i=0;i<marks.length;i++){
System.out.print("Enter mark: ");
marks[i] = sc.nextDouble();
}

for(int i=0;i<marks.length;i++){
System.out.print(marks[i] +"\t");
sum = sum + marks[i];
}
avg = sum / marks.length;
System.out.print("\nAverage: "+ avg);
}
}

Enter mark: 97.5


Enter mark: 75.3
Enter mark: 53.1
Enter mark: 86.4
Enter mark: 64.8
Enter mark: 42
Enter mark: 100
Enter mark: 57.9
Enter mark: 46.8
Enter mark: 90
97.5 75.3 53.1 86.4 64.8 42.0 100.0 57.9 46.8 90.0
Average: 71.38

Page 50
Practical 6 : Arrays

Task 6: Maximum

Problem Statement
Write a complete Java program which initialized a group of marks in an array as
follows:

97.5 75.3 53.1 86.4 64.8 42.0 100.0 57.9 46.8 90.0

Find the highest mark.

PrintHighest.java

class PrintHighest{
public static void main(String[] args){

double[] marks =
{97.5,75.3,53.1,86.4,64.8,42.0,100.0,57.9,46.8,90.0};

double highest = marks[0];

for(int i=1;i<marks.length;i++){
if(marks[i]>highest)
highest = marks[i];
}
System.out.print("Highest: "+ highest);
}
}

Highest: 100.0

Page 51
Practical 6 : Arrays

Task 7: Frequency

Problem Statement
Create a complete Java program which determine the number of odd and even
numbers based on ten (10) numbers entered by user.

import java.util.Scanner;

class FreqArray{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int[] arr = new int[10];
int even=0, odd=0;

System.out.print("Enter ten numbers: ");

for(int i=0;i<arr.length;i++){
arr[i] = sc.nextInt();
if(arr[i]%2==0)
even = even + 1;
else
odd = odd + 1;
}
System.out.println("No. of even: "+ even);
System.out.print("No. of odd: "+ odd);
}
}

Enter ten numbers: 1 2 3 4 5 6 7 8 9 10


No. of even: 5
No. of odd: 5

Page 52
Practical 6 : Arrays

Task 8: Exercise
1 Write a program to read 10 students’ marks into an array called marks,
and print the best student marks.

2 Write a program to read 10 students’ names and marks into two


respective arrays called names and marks, and print the best student
name and marks.

3 Write a Java program which finds the minimum element in the array.

4 Write a program which finds both the maximum and minimum elements
in the array, at the same time.

5 Write a program which asks the user for a value to look for in the array
and searches for the value in the array. The code should print "Found!" to
System out if the value exists, or "Not found" otherwise.

6 Write a program that takes a double array, a, and returns a new array that
contains the elements of a squared.

7 Write a program that takes an array of integers and returns the index of
the largest element.

8 Write a program that takes an integer parameter, n, and returns a boolean


array that indicates, for each number from 0 to n - 1, whether the number
is a prime number.

9 Write a program that takes an integer n and an array of integers, and that
returns true if the numbers in the array are all factors of n (which is to say
that n is divisible by all of them).

10 Write a program that takes an array of integers and two indexes,


lowIndex and highIndex, and finds the maximum value in the array, but
only considering the elements between lowIndex and highIndex,
including both.

Page 53
Practical 7 : Methods

Practical 7: Non-static
Methods (8 hours)
Learning Outcomes:

At the end of this lesson, students should be able to:


i. Construct programs that use standard and/or user-defined methods based
on given problem.

Task 1: Understanding the Concept of Methods


Methods must be defined before it is being called.

Method Definitions

Four (4) types of method defintions with examples:

Type 1. A method definition which return no value, receive no parameters


void showWelcome(){
System.out.print("Welcome to Java");
}

Type 2. A method definition which return no value, receive parameters


void sayHello(String name){
System.out.print("Hello "+ name);
}

Type 3. A method definition which return int value, receive no parameters


(this type of definition is rarely used)
int calcProduct(){
return 10*10;
}

Type 4. A method definition which return int value, receive parameters


int calcAdd(int x, int y){
return x+y;
}

Page 54
Practical 7 : Methods

Calling a Method

Before a method is called, we must create the object in order to call the specific
method. Object created using the statement,

ClassName obj = new ClassName();

where, ClassName is the name of the class, and obj can be any valid identifiers
to represent instance of the class.

Four (4) types of method calls based on method definitions with examples:

1. Calling a Type 1 method, receive no value, pass no arguments:


obj.showWelcome();

2. Calling a Type 2 method, receive no value, pass arguments:


obj.sayHello(String name);

3. Calling a Type 3 method, receive value, pass no arguments (rarely used):


obj.calcProduct();

4. Calling a Type 4 method, receive value, pass arguments:


obj.calcAdd(x, y);

For calling Type 3 and Type 4 method, usually these types of methods call either:

 Assign to a variable then display the result using the output statement, or
 Directly use output statement to display the output.

Page 55
Practical 7 : Methods

For example:

import java.util.Scanner;
class Arithmetic{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Arithmetic obj = new Arithmetic();

System.out.print("Enter your name and 2 numbers: ");


String name = sc.next();
int num1 = sc.nextInt();
int num2 = sc.nextInt();

obj.showWelcome();
obj.sayHi(name);
int result = obj.calcAdd(num1, num2);
System.out.print("Addition: "+ result);
}

void showWelcome(){
System.out.println("Welcome to Java");
}

void sayHi(String name){


System.out.println("Hello "+name);
}

int calcAdd(int x, int y){


return x+y;
}
}

Enter your name and 2 numbers: Amran 9 3


Welcome to Java
Hello Amran
Addition: 12

Page 56
Practical 7 : Methods

Template for Method Definitions and Calls

Return No Value Return a Value (int, double, boolean, char, String)


METHOD
Method Definition Method Call Method Definition Method Call

void myMethod1(){ obj.myMethod1() int myMethod3(){ tmp=obj.myMethod3()

Receive //method-body //method-body System.out.print(tmp);


No
Arguments } }

Type 1 Type 3

void myMethod2(int a){ obj.myMethod2(x) int myMethod4(int a){ System.out.print(obj.myMethod4(x));

//method-body //method-body
Receive
} }
Arguments Please read Page 55, for calling
Type 3 and Type 4 method.

Type 2 Type 4

Page 57
Practical 7 : Methods

Task 2: A Method Accepting No Arguments and Returning No


Value
Write a complete Java program which print out a message “I Love Computer
Science” from a method named printMessage().

MethodCall1.java
class MethodCall1{

public static void main(String[] args){


1
MethodCall1 mc = new MethodCall1();

mc.printMethod();

} 3
4

void printMethod(){

System.out.print("I Love Computer Science");

I Love Computer Science

*Note: mc is object or instance of class MethodCall1.

Explanation:

No. Description

1 Create object, mc from class MethodCall1

2 Use object, mc to call method, printMethod

3 Pass no arguments, () to printMethod

4 Call method, printMethod

Page 58
Practical 7 : Methods

Task 3: A Method Accepting No Arguments and Returning No


Value
Write a complete Java program which print out the following messages:

Message 1: I Love Computer Science


Message 2: I Like Programming
Message 3: I Learn Java

Message 1: I Love Computer Science will be printed from the main() method.
Message 2: I Like Programming will be printed from calling methodName1().
Message 3: I Learn Java will be printed from calling methodName2().

MethodCall2.java

class MethodCall2{
public static void main(String[] args){
MethodCall2 obj = new MethodCall2();

System.out.println("I Love Computer Science");


obj.methodName1();
obj.methodName2();
}

void methodName1(){
System.out.println("I Like Programming");
}

void methodName2(){
System.out.println("I Learn Java");
}
}

I Love Computer Science


I Like Programming
I Learn Java

*Note: The statement

MethodCall2 obj = new MethodCall2();

is a syntax to create object, obj from its class name MethodCall2.

Page 59
Practical 7 : Methods

Task 4: A Method with Arguments and Returning No Value


Write a complete Java program with method calling which display the following
output:

Hello, <yourname>

MethodCall3.java

class MethodCall3{
public static void main(String[] args){
MethodCall3 mc = new MethodCall3();

String name = "Amran";

mc.printName(name);
}

void printName(String a){


System.out.println("Hello, "+ a);
}
}

Hello, Amran

*Note: The statement

MethodCall3 mc = new MethodCall3();

is a syntax to create object, mc from its class name MethodCall3.

**Here, we can see that the object name can be any valid identifiers.

Page 60
Practical 7 : Methods

Task 5: A Method with Arguments and Returning No Value

Problem Statement
Write a complete Java program which accept name and age of a person, then
display the following output from the method named printNameAge():

Hello, <yourname>
Your age now is <age> years old

MethodCall4.java

import java.util.Scanner;
class MethodCall4{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
MethodCall4 tmp = new MethodCall4();

System.out.print("Enter name and age: ");


String name = sc.next();
int age = sc.nextInt();
tmp.printName(name,age);
}

void printName(String a, int b){


System.out.println("Hello, "+ a);
System.out.println("Your age now is "+ b +" years old.");
}
}

Enter name: Amran


Enter age: 40
Hello, Amran
Your age now is 40 years old.

 What is the object name for the class MethodCall4? ______________________

 Is the method call, in this program passed any arguments? If yes, name the
arguments. __________ ____________ ____________

 Name the parameters that receive the arguments passed. ______ ______

Page 61
Practical 7 : Methods

Task 6: A Method without Arguments and Returning Value


Write a complete Java program which find the square value of 10.

SquareMain.java

class SquareMain {

public static void main(String[] args) {

SquareMain sm = new SquareMain();

int result;

result = sm.square();

System.out.println("Squared value of 10 is: " + result);

int square() {

return 10 * 10;

Squared value of 10 is: 100

 Name one (1) object in this program.


__________________

 Give one (1) example of method definition and method call exists in this
program.

____________________________

____________________________

Page 62
Practical 7 : Methods

Task 7: A Method Accepting Arguments and Returning Value


Write a complete Java program which return the square of a number 3 and 4.

SquareMain.java

class SquareMain {
public static void main(String[] args) {
SquareMain sm = new SquareMain();

int result, n;

n = 3;
result = sm.square(n);
System.out.println("Square of 3 is: " + result);

n = 4;
result = sm.square(n);
System.out.println("Square of 4 is: " + result);
}

int square(int i) {
return i * i;
}
}

Square of 3 is: 9
Square of 4 is: 16

Which type the method square?

Page 63
Practical 7 : Methods

Task 8: A Method Accepting Arguments and Returning Value


Write a complete Java program which return the sum and the product of two
integers.

ArithmeticMain.java

class ArithmeticMain{
public static void main(String[] args){
ArithmeticMain am = new ArithmeticMain();

System.out.println("10 + 20 = " + am.getSum(10, 20));


System.out.println("20 x 40 = " + am.getProduct(20, 40));
}

int getSum(int i, int j){


return i + j;
}

int getProduct(int x, int y){


return x * y;
}
}

10 + 20 = 30
20 x 40 = 800

What is the object name for the class ArithmeticMain?

Which type the method getSum and getProduct?

Page 64
Practical 7 : Methods

Task 9: A Method Accepting Arguments and Returning Value


Write a complete Java program which takes int as a parameter. Based on the
argument passed, the method returns the squared value of it.

SquareMain.java

class SquareMain {
public static void main(String[] args) {
SquareMain sm = new SquareMain();

int result=0;

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


result = sm.getSquare(i);
System.out.println("Square of "+ i +" is : "+ result);
}
}

int getSquare(int x){


return x * x;
}
}

What is the output for the above program?

Page 65
Practical 7 : Methods

Task 10: Exercise

1 Create a non-static method,

(a) Write the first line of a method named myMethod that takes three
parameters: an int and two Strings.
(b) Write a line of code that calls myMethod, passing as arguments the
value 501, the name of your favorite colour, and the name of the
state you grew up on.

2 Create a non-static method,

(a) Write a method called printAmerican that takes the day, date,
month and year as parameters and that displays them in American
format.
(b) Test your method by invoking it from main and passing
appropriate arguments. The output should look something like this
(except that the date might be different):
Saturday, July 22, 2015
(c) Once you have debugged printAmerican, write another method
called printEuropean that displays the date in European format.

3 Write a method called square that takes an integer and returns an


approximation of the square of the parameter. Test the method using
main method.

4 Write a method named isNotDivisible that takes two integers, p and


q, and that returns true if p is not divisible by q, and false otherwise.
Test the method using main method.

5 Write a method named oddSum that takes a positive odd integer n and
returns the sum of odd integers from 1 to n. Test the method using main
method.

Page 66

Potrebbero piacerti anche