16
Basic Programs 1. Write down Java statements to declare a double variable salary with the initial value 17000.0, an boolean variable bold with no initial value, and an int constant NUM_WHEELS with the value 4. 2. The body mass index (BMI) of a person is defined as the ratio of body mass in kilograms to the square of body height in meter. For example, a person of 1.8m tall with weight 55kg has BMI 55/(1.8)2 = 16.975308641975307. A person with BMI between 20 and 25 is considered to have a healthy amount of body fat. A person with BMI of less than 20 is regarded as underweight, and one with a BMI of more than 25 is regarded as overweight. Write a program to calculate the body mass index (BMI) of the user. Ask the user for their height and their mass. Allow the user to enter both in inches and meters, and both in pounds and kilograms. Also output the meaning of the BMI. Note that 1kg = 2.2lb, and 1in = 0.0254in. Example input/output: What is your weight? 55 In lb or kg? (1=lb, 2=kg) 2 What is your height? 1.8 In in or m? (1=in, 2=m) 2 Your BMI is 16.975308641975307. You are underweight. 3. Write a method that takes a number between 0 and 9 as an argument and prints the number as a word on the screen. 4. Write a method that takes a number between 0 and 9 as a parameter and returns the number as a string from the method. 5. Write a method that takes a number between 0 and 9 as an argument and prints on the screen “Number green bottles standing on the wall” (where Number is replaced by the word version of the number). If the numeric parameter is 1 then your method should print bottle rather than bottles.

Mkp (PCIT4303) JAVA 5 IT 68 Java Assignments

Embed Size (px)

Citation preview

Page 1: Mkp (PCIT4303) JAVA 5 IT 68 Java Assignments

Basic Programs

1. Write down Java statements to declare a double variable salary with the initial value 17000.0, an boolean variable bold with no initial value, and an int constant NUM_WHEELS with the value 4.

2. The body mass index (BMI) of a person is defined as the ratio of body mass in kilograms to the square of body height in meter. For example, a person of 1.8m tall with weight 55kg has BMI 55/(1.8)2 = 16.975308641975307. A person with BMI between 20 and 25 is considered to have a healthy amount of body fat. A person with BMI of less than 20 is regarded as underweight, and one with a BMI of more than 25 is regarded as overweight. Write a program to calculate the body mass index (BMI) of the user. Ask the user for their height and their mass. Allow the user to enter both in inches and meters, and both in pounds and kilograms. Also output the meaning of the BMI. Note that 1kg = 2.2lb, and 1in = 0.0254in. Example input/output: What is your weight? 55 In lb or kg? (1=lb, 2=kg) 2 What is your height? 1.8 In in or m? (1=in, 2=m) 2 Your BMI is 16.975308641975307. You are underweight.

3. Write a method that takes a number between 0 and 9 as an argument and prints the number as a word on the screen.

4. Write a method that takes a number between 0 and 9 as a parameter and returns the number as a string from the method.

5. Write a method that takes a number between 0 and 9 as an argument and prints on the screen “Number green bottles standing on the wall” (where Number is replaced by the word version of the number). If the numeric parameter is 1 then your method should print bottle rather than bottles.

Page 2: Mkp (PCIT4303) JAVA 5 IT 68 Java Assignments

Control Statements

1. Consider the sequence of digits from 1 through N (N<=9) in increasing order: 1 2 3 4 … N Insert either a ‘+’ (for addition) or a ‘-‘ (for subtraction) between each of the digits so that the resultant sum is zero. Print all possible combinations that sum to zero. Example: Enter a number: 7 1+2-3+4-5-6+7=0 1+2-3-4+5+6-7=0 1-2+3+4-5+6-7=0 1-2-3-4-5+6+7=0

2. Write a program that reads a list of positive numbers < 100 and displays the largest and the smallest. A 0 (the number zero) should terminate the list. Do not use an array to answer this question. Do not use any methods either. There is at least one number before the 0.

3. If one looks at the square numbers and the differences between each adjacent pair of square numbers a pattern emerges. squares: 0 1 4 9 16 25 36 49… differences: 1 3 5 7 9 11 13… Write a program to print out the square numbers, ten to a line, without using multiplication *.

4. Write a method called absDiff, which takes two integers as parameters and returns the absolute value of the difference between the two integers.

5. Write a method called intRoot, which takes an integer as a parameter and returns the integer value closest to the square root of the parameter. Your method may call absDiff.

6. Given a sequence where the ith term is the closest integer to the square root of i, write a method called printSequence, which takes an integer n as a parameter and prints on the screen the first n integers in the sequence, ten to a line. You may use previously written and inbuilt methods. So printSequence(10) would print on the screen: 1 1 2 2 2 2 3 3 3 3

7. Write a method numFound that takes two integers n and m and returns the number of occurrences of m in the sequence of the first n integer square roots. So numFound(10,3) is 4 numFound(10,1) is 2 numFound(10,5) is 0 You may use previously written and inbuilt methods.

8. All characters in Java have numeric values (called ASCII values). The numeric value for ‘A’ is 65, ‘B’ is 66 etc. and ‘a’ is 97, ‘b’ is 98 etc. The following method is legal Java and returns 0

int meth(){ char c = 'a'; return c - 97;

}. a. Write a method convert that takes a character and returns an integer. If the character is a

letter then it returns its position in the letters. So convert(‘A’) returns 1 and convert(‘z’) returns 26. If the character is not a letter than convert should return –1.

b. Write a program that reads in a passage of text terminated by EOF and prints out the number of times each letter occurs. The passage should ignore anything that is not a letter. It should treat upper and lower case letters as the same letter. You may call convert from part a of this question. Write your code so that given the same input it would produce the same output as the following example execution:

Please type in your text -->Hello sweetie 0 0 0 0 4 0 0 1 1 0 0 2 0 0 1 0 0 0 1 1 0 0 1 0 0 0

Page 3: Mkp (PCIT4303) JAVA 5 IT 68 Java Assignments

9. Write a method smallestFactor that accept an integer argument, and return the smallest factor larger than 1 of this number. It should return the argument itself if it is a prime or it is 1, and return 0 if it is not positive.

10. By calling the method you’ve written in Q9 , write the main method of a program that read a number from the user and completely factorize it.

Page 4: Mkp (PCIT4303) JAVA 5 IT 68 Java Assignments

Array

1. A secret code encrypts a message by putting it in an array and reading down the columns

(blanks are replaced by asterisks and full stops are added to fill up the array). Write a program that encrypts an input string. (For extra marks write a program that decrypts a given string using the rules outlined above.)

LETS*G O*TO*T HE*SAN DWICH* SHOP*T ODAY.. Example: Input: “Lets go to the sandwich shop today” Output: “Lohdsoe*ewhdtt*ioasoscpy**ah*.gtn*t.”

2. To sort a list of integers using selection sort. 3. Given 2 arrays A & B of integers, which are unsorted, write a program to merge them into a

single sorted array C that contains every item from arrays A & B.

Page 5: Mkp (PCIT4303) JAVA 5 IT 68 Java Assignments

Class

1. Write a class called Account with following attributes name, accountNumber, balance, address. Use appropriate data types for these attributes. Use access control to prevent direct access of these attributes from outside the class. Write methods that allow you to read these variables and also change them (if change is permitted). Write another class called AccountDemo and instantiate an object of Account class. Test your methods and print values eg: String getName( ) & void setName(String name) create all the methods following the above naming convention

2. Create a class called Calculator and write another class called CalculatorDemo (contains main method). Provide support for following methods in the Calculator class Prototypes: int add(int , int) ; int substract(int, int); int multiply(int, int); int divide(int, int); Create an instance of Calculator and then invoke the above methods from CalculatorDemo.

3. Declare a variable Student which consists of a person's name, mark for Programming, for Logic and a grade for Lab. A mark is a number (between 0 and100) and a grade is a letter (between A and F). Write a predicate (a boolean method) isStronger, which takes two students and returns true if and only if the first student has done better than the second in the ordering below.

a. the Programming mark is most important, b. numerical order of Maths marks is the determining factor when two students have the

same Programming mark, c. alphabetical order of Lab grades is the determining factor when two students have the

same Programming and Maths marks. 4. Suppose we want to represent a planet in the solar system as an object of class Planet. In the

object, it contains two fields: one called name is a String containing its name, and one called satellites is an array of String containing the names of all its satellites. Define the class, with a constructor taking a String and an array of String as argument for initializing the object.

5. For the last question, write a method print() in the class to print out the name of the planet and all the satellites. For example, if we have

String[] earth_sat = { "Moon" }; Planet earth = new Planet("Earth", earth_sat); Then we want earth.print(); to print out the following: Earth has 1 satellite(s): Moon.

6. When creating an array, we need to know the exact size of the array when the array is created. There is no way to expand or contract an array afterwards. There are many applications that want a “resizable” array, because the exact number of elements is not known when the array is created. This can be achieved in Java by reallocating an array whenever the original array is not sufficient to hold the array. When this happens, we copy all the elements from the old array to the new one. Write a Java class for representing a resizable array of integers. The class, called IntArray, should have the following constructors and methods. Here ia denotes a reference to IntArray.

• Constructor: IntArray(initial_size), where initial_size is an integer specifying the initial size of the array. All elements are initially 0. • Read: intAt(index): return the integer stored in the array at the integer index index. A run-time error should be generated if index is out of range. • Write: storeAt(index, value): store an integer value into the array at the integer index index. Return nothing. A run-time error should be generated if index is out of range.

Page 6: Mkp (PCIT4303) JAVA 5 IT 68 Java Assignments

• Size: getSize(): return the current size of the array. • Resize: resize(size): change the capacity of the array to an integer size. If size is different from the current size of the array, a new array should be allocated, and the old content of the array should be copied to the new array. If size is smaller than the original size, the extra elements in the original array are lost. If size is larger than the original size, the extra elements in the new array takes the value 0. Return nothing. • Write and resize: storeAndResize(index, value): store an integer value at an integer index index. If index is larger than or equal to the current size of the array, it also expand the array. If this happens, the array is expanded to either a size of index+1, or double the original size, whichever the larger. A run-time error should be generated if index is negative. Return nothing. With this class, write a program that reads integers until it reads -1, and prints out the median of the integers read (not counting -1). For example: Type the numbers, terminated by -1: 2 9 8 3 7 6 -1 The median is 6.5.

7. Create an abstract class called Animal and create at least three classes ( Dog, Snake, Fish etc.,) which extend from that class and override the abstract methods defined in animal class. (Print different values for different animals when you override methods in Animal class)

public abstract class Animal{ public abstract void move(); public abstract void eat(); public void sleep(){

Sys.println(“i am sleeping”); }

} Then create another class called AnimalDemo and write a method called with the following signature:

live(Animal); In this method invoke some methods of Animal. Your main method should be written in AnimalDemo class.

8. Go through the following classes and follow the instructions given below: class Hello{

String name; private Hello( String name){

this.name=name; } public void sayHello( ){

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

} Save the above class to a file. Try to create an object of this class in another class say

HelloDemo (contains main method) and invoke sayHello( ) methods on that object. note: you are not permitted to add constructors or modify the existing constructors hint: use static

Page 7: Mkp (PCIT4303) JAVA 5 IT 68 Java Assignments

9. Write a class called Gen which contains an instance variable called id (say of type int). Now whenever an object is created, id has to be assigned a unique value. This has to be assigned in incremental fashion. Do not set this id manually after creation of the object. Do not use parameterized constructors.

10. Design a class called Single keeping in mind the following constraints. Only a single instance of the class should be allowed to create and same instance should be made to share by all the clients. (Clients here refer to the classes which use the class Single). You should ensure that no additional instances are created accidentally. (Hint: use static)

Page 8: Mkp (PCIT4303) JAVA 5 IT 68 Java Assignments

Inheritance 1. Design the class hierarchy. Add your own methods.

StaffCode Name

TeacherSubject

Publication

OfficerGrade

Typist

Speed

Regular

Salary Casual

Daily wages

Page 9: Mkp (PCIT4303) JAVA 5 IT 68 Java Assignments

Package & Interface 1. Define a class UString which contains method for the following statement.

a. To reverse the given string b. To give the number of alphabets in a string.

Create a package and include this class in the created package. Import this package in to java source file and perform string operations.

c. To extract a portion of character string and print the extracted string. Assume that m characters are extracted starting with the nth character.

d. To read a text and count all occurrence of a particular word. e. To read a string and rewrite it in the alphabetical order

( Ex ;- STRING --->GINRST) 2. Create a package by name logicgate which consist of classes for AND, OR, NOT gate, import

this package in to java source file and simulate the behavior of half adder circuit. 3. Create a package called shapes. Now write a class called Point (belongs to package shape)

which represents a point in 2D-space. It has two fields x and y. Write a parametrized constructor to initialize these values(do not provide default constructor). ---> Now write another class called Circle (belongs to package shapes) which has a field of type Point (to represent the center of circle) and another field radius. Write a parametrized constructor to initalize all fields of circle. Now write a method in this class called isInside() which takes a point as parameter and returns true if that point is inside the circle or false otherwise. ---> Now write main method (in CircleDemo class), create a circle and invoke isInside() method by passing a parameter to it and print the return value. we will have Three classes Point, Circle and CircleDemo (contains main method) Point(int x, int y){ } //parametrized constructor Circle(Point centre, int radius){ } //parametrized constructor boolean isInside(Point p) CircleDemo doesn’t belong to shapes package.

4. Assuming you have the following interface: public interface Sort{

public void sort(int elements[], int start, int end); public void sort(int elements[]); //equivalent to calling sort(elements, 0, elements.length-1)

} Implement this interface with an AbstractMergeSort class: public abstract class AbstractMergeSort implements Sort {

public void merge(int a[], int b[], int mergedandb[]) { //Your Code here.

}

public void sort(int elements[]); { //Your Code here.

} } Now extend the abstract class with a concrete MergeSort class: public class MergeSort extends AbstractMergeSort {

Page 10: Mkp (PCIT4303) JAVA 5 IT 68 Java Assignments

public void sort(int elements[]) { //Your Code here.

} Now implement a SorterTaskThread which can invoke MergeSort on a part of the array: public class SorterTaskThread extends Thread {

public SorterThread(int elements[], int start, int end) { //Your Code here.

} public void run() {

//Your Code here. }

} Now extend the ParallelMergeSort from the AbstractMergeSortClass class, and make it invoke as many SorterTaskThread s as required: public class ParallelMergeSort extends AbstractMergeSort {

private static final int NUM_THREADS=2; public void sort(int elements[]) {

//Your Code here. }

} Now finally implement class MergeSortTester; Randomly populate an array of 200 elements using Math.random()*123456. Sort the array using MergeSort, then using ParallelMergeSort. Now run both implementations and test the time using this command: test java MergeSortTester Sample the times taken for 10 times, average it. Now find the ratio of time for MergeSort/time for ParallelMergeSort. If it's <1, why is it so? Now repeat the same with 200000 elements. Does the ratio change?

Page 11: Mkp (PCIT4303) JAVA 5 IT 68 Java Assignments

Exception Handling

1. Save the above class to a file and compile it and check the output. class A{ public static void main(String[] args){ int a,b; try{ a=0;b=1; System.out.println(b/a); //return; }catch(Exception){ System.out.println(“Exception caught”); //return; }finally{ System.out.println(“in Finally”) } //System.out.println(“at the end”);

} }

Now uncomment the comments one by one and observe the outputs and understand all the cases.

2. Write a class called BankAccount with the following properties and methods. Properties: name, PIN, balance methods: deposit(int amt), withdraw(int amt) write another class called ATM with following methods and properties: methods:deposit(Account acc, int amt), withdraw(Account acc, int amt) , transfer(Account acc1, Account acc2, int amt)

Assume that an account needs to have a minimum balance of 200. If an attempt is made to withdraw, which results in balance going below 200, throw an exception called MinimumBalanceException. For this you need to create your own exception class.

Note: To create an Exception class called MyFirstException class MyFirstException extends Exception{ /*I never thought it’s so simple*/ } Use throw and throws wherever necessary.

Page 12: Mkp (PCIT4303) JAVA 5 IT 68 Java Assignments

3. Write a java program to compare names of two persons (first name and last name) and return

result as a. Fully matched if both first and last names are same b. Same first names if only first name matches c. Same last names if only last name matches d. No match otherwise. e. NameFormatException if any of the Person name has any illegal entry ... e.g numbers within name or name consisting of three parts

Page 13: Mkp (PCIT4303) JAVA 5 IT 68 Java Assignments

Multithreading 1. Define a class that implement runnable interface. Write a java program to create three threads.

First thread prints squares, second thread prints cubes and third thread prints roots of natural numbers.

2. Four missiles are test fired at a research centre such that every missile fires four firing components FC1 , FC2 , FC3, FC4. The missiles have a serial arrangement and they are fired one after another with a delay of 1500ms.The components are automatically shot within the allotted timeslot with uniform delay. A timer program (written in java) from the trigger interface displays the time of firing of different components of different missiles (may be named missile1, missile2 , missile3 & missile4) Using threads implement the timer program in java to display the times at which each missile and its component are fired.

Sample output : Timer reading : 0ms – missile1 ready Timer reading : 300ms – FC1 fired Timer reading : 600ms – FC2 fired Timer reading : 900ms – FC3 fired Timer reading : 1200ms – FC4 fired Timer reading : 1500ms – missile2 ready Timer reading : 1800ms – FC1 fired

3. A relay circuit has two types of components Major component and Minor components to ring relayed alarm bells. The design is such that for every Major bell ring 3 Minor alarms ring.Using threads implement the above scenario for a timed output as below :

Time : 0s Major alarm fired Time : 10s Minor alarm1 fired Time : 20s Minor alarm1 fired Time : 30s Minor alarm1 fired Time : 50s Major alarm fired

Page 14: Mkp (PCIT4303) JAVA 5 IT 68 Java Assignments

Applet / AWT / SWING

Page 15: Mkp (PCIT4303) JAVA 5 IT 68 Java Assignments
Page 16: Mkp (PCIT4303) JAVA 5 IT 68 Java Assignments