2100(Aug15) Tutorials_Complete Set

16
Tutorials Page 1 of 16 Tutorial 1 – Input & Output 1. Write a program to display the following information: Name : Your name ID : J02005300 Programme : Diploma in Communication Technology Subject : CSC2100 2. Write a program to input two positive integers and calculate and display their addition, subtraction, multiplication and division. 3. Write a program to read in a value in seconds (the value range from 1 to 10,000). Convert and print out the seconds in hours, minutes and seconds format (0:00:00). 4. Write a program to read an amount in RM and convert it to the currencies listed below: Sing Dollar (SingD 1 = RM 2.6) US Dollar (USD 1 = RM 3.12) Pound (£ 1 = RM 6.4) Yen (100 ¥ = RM 30) Yuan (RM 1 = 1.8 Yuan) Rupiah (RM 1 = 2700 Rupiah) 5. Write a program to calculate the cost to tile a floor. The size for a tile is 12 cm x 12 cm. The tiles are sold in boxes. One box of tiles is $36.50. One box consists of 12 pieces. Read in the width and length of the floor in cm from the user and display the cost to buy the tiles. Calculate also the labor cost to tile the floor where the labor is charged $ 5 per cm 2 . 6. A company is selling X brand water filter at the price of RM 979 per unit. Its salespersons receive a commission of 5% from the total sales (total sales = selling price * units sold) they perform. On top of that, they are also given a basic salary of RM700 per month. Write a program that inputs the number of units sold by a salesperson in a month and display his/her commission earned and total salary (basic + commission) received for the month. 7. Write a program to read in the length of the shorter sides (a and b) of a right triangle and calculate the length of the longest side (c) of the right triangle. Given that c 2 = a 2 + b 2 c a b

description

Java

Transcript of 2100(Aug15) Tutorials_Complete Set

Page 1: 2100(Aug15) Tutorials_Complete Set

Tutorials Page 1 of 16

Tutorial 1 – Input & Output

1. Write a program to display the following information:

Name : Your name ID : J02005300

Programme : Diploma in Communication Technology Subject : CSC2100

2. Write a program to input two positive integers and calculate and display their addition, subtraction, multiplication and division.

3. Write a program to read in a value in seconds (the value range from 1 to 10,000). Convert and print out the seconds in hours, minutes and seconds format (0:00:00).

4. Write a program to read an amount in RM and convert it to the currencies listed below:

Sing Dollar (SingD 1 = RM 2.6)

US Dollar (USD 1 = RM 3.12) Pound (£ 1 = RM 6.4)

Yen (100 ¥ = RM 30) Yuan (RM 1 = 1.8 Yuan)

Rupiah (RM 1 = 2700 Rupiah) 5. Write a program to calculate the cost to tile a floor. The size for a tile is 12 cm x 12 cm. The

tiles are sold in boxes. One box of tiles is $36.50. One box consists of 12 pieces. Read in the width and length of the floor in cm from the user and display the cost to buy the tiles. Calculate also the labor cost to tile the floor where the labor is charged $ 5 per cm2.

6. A company is selling X brand water filter at the price of RM 979 per unit. Its salespersons receive a commission of 5% from the total sales (total sales = selling price * units sold) they perform. On top of that, they are also given a basic salary of RM700 per month. Write a program that inputs the number of units sold by a salesperson in a month and display his/her commission earned and total salary (basic + commission) received for the month.

7. Write a program to read in the length of the shorter sides (a and b) of a right triangle and

calculate the length of the longest side (c) of the right triangle. Given that c2 = a2 + b2

c

a

b

Page 2: 2100(Aug15) Tutorials_Complete Set

Tutorials Page 2 of 16

Tutorial 2 – Expression and validation

1. What are the values of the following expression? (a) 6 / 3 * 7 (b) 7 * 6 / 3 (c) 28 / 5 (d) 16 % 2 (e) 28 % 5 (f) 28 % 3 * 5 + 1 (g) 20 / (4 + 1) (h) 18 / 2 + 14 / 2

2. What is the value of each of the following boolean expression? (a) 4 >1 (b) 5 <= 15 (c) 43 <= 43 (d) 2 = = 3 (e) 2 + 5 = = 7 (f) 3 + 8 < = 10 (g) 3 != 9 (h) 13 ! = 13 (i) -4 ! = 4 (j) 2 + 5 * 3 = = 21

3. Are the following identifiers valid? (a) applet (b) Applet (c) a++ (d) --a (e) 4#R (f) #44 (g) apps

4. Declare the following (a) an int variable with an initial value of 0 (b) a long variable with an initial value of 10000 //long population = 10000L; (c) a float variable with an initial value of 3.4 //float f=3.4f; (d) a double variable with an initial value of 34.45 //double d=34.45; (e) a char variable with an initial value of 4 //char c= ‘4’; (f) a boolean variable with an initial value of true //boolean b=true;

Page 3: 2100(Aug15) Tutorials_Complete Set

Tutorials Page 3 of 16

5. Find the largest and smallest byte, short, int, long, float, and double.

6. Are the conversions shown below valid or invalid? If valid, what is the result? (a) char c = 'A'; int i = c; (b) boolean b = true; int i = (int) b; (c) float f = 1000.34f; int i = (int) f; (d) double d = 1000.34; int i = (double) d; (e) int i = 1000; char c = (char) i; (f) int i = 1000; boolean b = (boolean) b;

7. Write a statement or comment to accomplish each of the following: (a) state that this program will calculate the product of 3 integers. (b) name the class name as Calculate (c) declare the variable x, y and z to be of type int. (d) initialize the variable x and y to be 3, and 4. (e) assign the result of addition of x and y to variable z. (f) print out the result as x + y = z.

8. Assume the following:

a = 2, b = 3, c = 4

Evaluate the following expressions:

i. y = c-- + ++b * ++c + b++ * 2 ii. y = ++c * --c + a++ * b-- - a-- iii. y = b++ - ++b + a-- * --c

9. Assume a = 1, and d = 1.0, and each of the expression is independent. What are the results of the following expression

(a) a = 46/9 (b) a = 46%9+4*4-2 (c) a = 45+43%5*(23*3%2) (d) a = 45+45*50%a -- (e) a = 45+1+45*50%(a--) (f) d-= 3.4*(a+5)*d -- (g) a%=3/a+3

Page 4: 2100(Aug15) Tutorials_Complete Set

Tutorials Page 4 of 16

Tutorial 3 – Control Structures

1. Write a program to read a character. The program should indicate whether the entered character is vowel or consonant. Your program should apply case statement and is able to recognize both uppercase and lowercase

2. Write a program to read in a subject’s marks from the student. Use the following table to display the grade obtained by the student.

Marks Grade

70 to 100 56 to 69 40 to 55 0 to 39

A B C D

3. Write a program using for loop to produce the following series:

(a) 3 6 9 12 15 18 (b) 1 3 6 10 15 21 (c) 1 4 9 16 25 36 (d) 0 2 6 12 20 30 42

4. Write a program to calculate the first value of N where the total of 12 + 22 + 32 + ….. + N2 exceed 1000.

5. Write a program that uses loop structure to produce the multiplication table of 3 and print it in a message box as shown below:

Page 5: 2100(Aug15) Tutorials_Complete Set

Tutorials Page 5 of 16

6. Joe deposits RM100000 to a bank with the interest 10% compounded annually. At the end of the year, right after the interest is added, Joe will withdraw RM12000 from the bank. Assume that Joe never deposits any money throughout the years since the first time. Calculate how many years the bank allows him to do such a withdrawal.

7. Write a program to produce the following pattern: (a) # # # # # # # # # # (b) @@@@@ @@@ @

8. Write a nested for loop that will print the following output: 5

4 5 3 4 5

2 3 4 5 1 2 3 4 5

9. Write a program to read in a number and display all its factors. For example, the factors for integer 12 are 1, 2, 3, 4, 6 and 12.

10. Write a program to read in a 5-digit integer from the user. If the input value is not a 5- digit number, ask to user to reenter the value. Your program then displays its first digit, third digit and last digit on screen.

Below shows the sample output of the program

Please enter a 5-digit integer: 235

Your input is not a 5-digit number, please enter again: 57924

The first digit is 5

The third digit is 9

The last digit is 4

Page 6: 2100(Aug15) Tutorials_Complete Set

Tutorials Page 6 of 16

Tutorial 4 - Methods

1. Write a program that reads a positive integer. The program then passes the integer to a method to determine and return the result if it is a prime number. The answer is displayed on screen.

2. Write a program that store all the 26 alphabet (a – z) into an array of char. Randomly pick an alphabet from the array and ask the user to guess the picked alphabet. Show appropriate message (“Correct” or “Wrong”) based on the input. User is given maximum of 3 guesses before the program shows the correct answer.

3. Write a program to accept a value from the user, use a method to accept the value and return the reverse of the number. For example, if the input number is 7631, the method should return 1367. Display the answer in main().

4. Write a program that uses a recursive method to compute the sum of the digits of an integer. Use the following declaration for the method:

int sumDigits(int n)

For example, sumDigits(234) returns 2+3+4 = 9. The program should prompt the user to enter an integer value and display the sum of the digits.

5. Write a program that reads two values: base and exponent from user and uses recursive method called power () to calculate and return the value of baseexponent. Display the answer on screen in main().

6. Given that the values on a series are: 8, X, 5, -2, 7, -9, 16, ….

8 and X are base numbers. 5 is derived from 8 - X. Write a complete java program with two methods: main method and recursive method. Use main method to read in the position of the series requested by the user and display the value accordingly. Use the recursive method to calculate and return the value of the position required by the user. For example, if the user wishes to know the value of position 7 on the series, the recursive method will return “16”.

Page 7: 2100(Aug15) Tutorials_Complete Set

Tutorials Page 7 of 16

7. Write a recursive method named range that takes two integers: min and max, and print all the integers between min and max. For example, if min is 2 and max is 7, the method will print the following as output:

2 3 4 5 6 7

8. Given the first infinite even number series:

-30, -28, -26, -24, …

And the second infinite integer series:

x1, x2, x3, x4, x5, …

where x1 is the fiftieth (50th) value on the first series and x2 = x1-3, x3 = x2-3 and so on.

Write a program with main method and two recursive methods for these two series. The first recursive method returns the 50th value of the first series. The second recursive method returns the value for x100. The second recursive method makes use of the first recursive method to find out the value for x1. Invoke the second recursive method in the main method do display the value for x100.

Page 8: 2100(Aug15) Tutorials_Complete Set

Tutorials Page 8 of 16

Tutorial 5 – Fundamental of Classes

1. Write a class named Account that has two attributes: balance (double) and

interestPercentage (int). The class has a method called addInterest that will calculate and add the interest value to the balance based on the interest percentage. Write a client program that instantiate an object of Account. Read the balance and the interest percentage from the user to be initialized to the object. Perform the add interest process by calling the addInterest method and display the balance after the interest is added.

2. Define a class named Computer. The class has the following members: o brand (String) and cost (double) as private attributes (1 mark) o a non-argument constructor that initializes the brand to “IBM” and cost to zero

(2 marks) o An overloading constructor that initializes the attributes using the incoming

arguments (3 marks) o mutator and accessor methods for attribute cost (5 marks) o calcSellingPrice() that receives a floating-point (double) value representing a

profit rate. It should calculate and return the selling price. For example: if the cost is RM2,000 and the profit rate is 0.4 (40%), then the selling price should be RM2,800 (4 marks).

The profit rate and price shall be positive value. Write a program with main method that instantiates a Computer object defined above and assign the following values to the object: brand = Dell and cost = 1580. Display the cost and the selling price of the computer if the profit rate is 0.4. Use the object methods to get the result. Change the cost to 1460 and display the cost and selling price again with this round the profit rate set to 3.5.

Page 9: 2100(Aug15) Tutorials_Complete Set

Tutorials Page 9 of 16

Tutorial 6 – Advanced Concept of Classes

1. Create a class named Shirt with data fields for collar size and sleeve length. Include a

constructor that takes arguments for each field. Include a class variable material and initialize it as “cotton”. Write a client program to instantiate two objects from the class with different collar size and sleeve length. Display all data including type of material for each shirt. Use method shirtDisplay() to display the data.

2. The Computer Science Division will be organizing a software design competition and you

are required to create an application to capture the registration information. You are required to create the following class named CompetitionEntry. The class has the following members:

two privates attributes : projectTitle (String) and teamSize(int)

one static attribute feePerParticipant (double) with initial value of RM6.50

a non-argument constructor that initializes as below:

projectTitle = “N/A”;

teamSize = 0;

An overloading constructor that initializes the attributes using the incoming arguments (3 marks)

Mutator and accessor method for attribute teamSize. Ensure that teamSize takes only positive value.

A computeTeamFee() method that returns the total fee by multiplying teamSize with feePerParticipant

Write a program to create CompetitionEntry object defined above and initialize the object (using constructor) with the following values: “Super Tech” for title and team size is 5. Display the total team fee on screen. Change the team size to 6 and display total team fee again. All changes and display should go through object methods.

3. Write the following classes to show the concept of object composition: A class Engine with two private data fields: type (String) and horsepower (double). It has setter and getter methods for the private variables. A class Car that has two private data fields: engine (Engine) and model (String). It has getter and setter methods for the two private variables. The setter method for variable engine takes the Engine type as the argument whereas the getter method for variable engine returns the engine of a car Produce a client program that creates objects of Car and Engine. The program reads the required data from the user to initialize both objects. The program then displays the details of the car including its horsepower and type of engine on screen.

Page 10: 2100(Aug15) Tutorials_Complete Set

Tutorials Page 10 of 16

Tutorial 7 - Arrays

1. Create two single-subscripted arrays A and B that store 10 values each. Randomly assign integers between 51 and 100 for the array A and 1 to 50 for array B. Read in an operation (plus or minus) from user to be performed on to the two arrays. Display the result of the operation on screen.

2. A company has 6 salespersons on duty during a promotion week (5 days). The manager would like to know the total sales (in RM) for each salesperson for the promotion week, and the total sales for each day for the week. Write a program that reads all the total sales for each salesperson for each day into a two-dimensional array with the days of the week as the columns and salesperson as the rows. Calculate and display the result.

3. With the following 2-dimensional array declaration and values initialization:

int [ ] num = { {15, 32, 6, 47, 63},

{7, 19, 33, 25},

{66, 39, 41, 78, 56, 54},

{6, 3, 8}

};

Write the program that has the above array and declares another array of int with 4 elements. Using a nested loop structure, the program is able to find and store the biggest value amongst the elements for each first-dimensional array (each row) in the num array. Display all biggest values on screen.

4. Write a program that will store daily temperatures (average) for the month of January 2012 into an array. Declare the array as double of size 31 and read the data from the user. Using the information, find and display the

(i) Hottest and coolest temperature of the month (ii) The difference between hottest and coolest temperature of the month (iii) The average temperature of the month

5. Write a program to create two two-dimensional arrays: X (3 by 2) and Y (2 by 3). Read the values from the user to be assigned into the arrays. Perform the multiplication on to the two arrays and display the result of X *Y in matrix pattern on screen.

Page 11: 2100(Aug15) Tutorials_Complete Set

Tutorials Page 11 of 16

Tutorial 8 - Inheritance 1. Create a class Employee that has name and title. Provide a constructor that takes in

arguments and getDetails( ) method that returns all the details of the employee. Create a subclass Worker which derived from Employee with additional attributes: hour and rate. Provide a constructor in Worker class. Provide also getSalary() method that returns the salary (hours * pay rate) of the worker and getDetails( ) method that returns the name, title (worker), hours, pay rate and salary. Create a class Client to instantiate an object of Worker. Display its values on screen.

2. Write a Java program to demonstrate the concept of inheritance by writing the following

classes: class Vehicle with three attributes: type, color, and number of wheels. It has a

method display( ) which is used to display the properties of the object created from this class.

class Car that derived from class Vehicle which has its property: number of doors and also an overriding method display( ) that displays all its properties (type =“Car”, color, number of wheels = 4, and number of doors)

class Bike that derived from class Vehicle with its property: the engine power (value in CC) and also the overriding method display( ) that displays all the details of the Bike (type = “Bike”, color, number of wheels = 2, power (in CC)).

class Client that instantiates one object of Car and one object of Bike by reading the necessary data from the user and displays all the details of the two objects on screen.

3. A class Continent that has the following members:

Two protected instance variables continentName and countriesNo that are used to store the name of the continent and the number of countries in that continent

A constructor that takes arguments for object initialization

A toString() method that returns the detail of a Continent

A class Country that derives from class Continent which has the following members:

Two private instance variables countryName and population

A constructor that takes necessary arguments for all its attributes

An overridden toString() method that returns the detail of a Country including its continent name

Write the program for the above classes. Create a client program that creates an object of Country and initializes the continent name, number of countries, country name and population with the values “Australia”, 1, “Australia” and 22118256 respectively. The program then displays the detail of the country on screen using the toString() method defined in class Country.

Page 12: 2100(Aug15) Tutorials_Complete Set

Tutorials Page 12 of 16

4. A class Door has one private attribute material (String). The class has constructor that takes data for attribute material. It has toString method that returns in String the information of a door. A class GlassDoor is the child class of class Door. Class GlassDoor has private attribute type (String). It has a constructor that assigns the material to “glass” and takes argument for attribute type. It has toString method that returns the information of a glass door’s material (by accessing parent class’s toString method) and type. Write the code for both classes

Page 13: 2100(Aug15) Tutorials_Complete Set

Tutorials Page 13 of 16

Tutorial 9 - Polymorphism

1. Create an abstract class Shape that has two data members: shapeTitle and

shapeDimension and one abstract method named area(). Provide a constructor that takes in arguments for shapeTitle (eg: circle, rectangle) and shapeDimension (2D/3D). Provide also a getDetails( ) method that displays the shape title and shape dimension. Create two subclasses: Circle and Rectangle which derived from Shape. Circle has an additional attribute: radius. Whereas Rectangle has two additional attributes: width and height. Provide a constructor in both subclasses that take arguments for their objects and pass necessary information to its superclass’s constructor. For Circle class, the fixed information to be passed to superclass’s constructor is “Circle” for shape and “2D” for shape-Dimension. For Rectangle class, the fixed information to be passed is “Rectangle” for shape and “2D” for shape-dimension. Both Circle and Rectangle classes also implement area() methods that return the area of their objects and override the getDetails() methods by displaying their attributes (radius or width and height) and their details (shapeTitle and shapeDimension) Create a class Client to instantiate both objects of Circle and Rectangle by reading the radius for a circle and width and height for the rectangle objects. Display their information on screen.

2. Write an application to demonstrate the concept of polymorphism by writing the

following classes:

abstract class Animal that consists of one protected data field: species (String); an abstract double dailyCost( ) method that is for the purpose of daily expense computation of an animal; and one display() method that is used to display the animal’s species.

final class Dog that derived from class Animal and has a constructor that passes the value “Dog” to its superclass’s constructor and a dailyCost() method that returns $8 for the daily cost. It also override the display() method by displaying the details of a Dog.

final class Bird that derived from class Animal and has a constructor that passes the value “Bird” to its superclass’s constructor and a dailyCost() method that returns $3 for the daily cost. It also override the display method by displaying the details of a Bird.

class Client that creates two objects: Dog and Bird. It demonstrates the concept of polymorphism by displaying the details (name, species and daily cost) of the two objects using the superclass’s reference.

Page 14: 2100(Aug15) Tutorials_Complete Set

Tutorials Page 14 of 16

Tutorial 10 – Interface

1. Create an interface called Rate. The interface has two constants named EMPLOYER_RATE

with the value 0.12 and EMPLOYEE_RATE with the value 0.08. It has a method payment() that has return type of double.

Create a class named EPF that implements the above interface. The EPF class has a private instance variable employeeSalary (double). It has also getter method to return the salary value and setter method to set the value of the salary. It implements the payment() method by calculating and displaying the EPF payment amount by both employee and employer based on the salary of the employee. Build a client program that instantiate an EPF object and read the value of the salary to be assigned to the object. Display the salary and the EPF payment by the employee and the employer.

2. Create an abstract class Shape that has two data members: shapeTitle and shapeDimension and one abstract method named area(). Provide a constructor that takes in arguments for shapeTitle (eg: circle, rectangle) and shapeDimension (2D/3D). Provide also a getDetails( ) method that displays the shape title and shape dimension.

Page 15: 2100(Aug15) Tutorials_Complete Set

Tutorials Page 15 of 16

Tutorial 11 - Strings

1. Write a program that reads two words from the user. Separate the words and display them

in two lines. For example: if the input is “Tuesday morning”, then the output should be: First word :Tuesday Second word :morning

2. Write a program to read in a sentence and a character. The program then finds and

displays the number of times the character occurs in the sentence.

3. Write a program to read in (i) a sentence, (ii) a word in the sentence and (iii) another word

to replace the previous word. For example, if the sentence is “How are you?”, the word is “How” and the replacement is “Where”, then your output should be “Where are you?”.

Page 16: 2100(Aug15) Tutorials_Complete Set

Tutorials Page 16 of 16

Tutorial 12 – Exception Handling

1. Write a program that read two numbers from the user. The program then display the

division result of the two numbers. Write a separate method called division() that accepts two parameters (type double). The method then returns the division result by dividing the first value with the second value. The method is able to handle exception when the divisor is zero and return zero as the result.

2. Write a program that stores the 12 names of the months (January to December) into an array. The program then input an integer between 1 and 12 from the user to display the name of the month (1 for January, 2 for February and so on) by accessing the array. Include exception handling in your program to handle the assessment of the array element which is given by the user. Display the error message “invalid range” if the input is not between 1 and 12 and repeat the input again.