Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
23 views15 pages

Java 020-2

The document is a lab manual for Object Oriented Programming 1 at The Hashemite University, containing various worksheets with programming exercises in Java. It covers topics such as input/output, selection statements, repetition statements, methods, arrays, and classes, with specific tasks for students to complete. Each worksheet includes multiple questions that require writing Java programs to solve problems related to the concepts taught in the course.

Uploaded by

saifalhomimat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views15 pages

Java 020-2

The document is a lab manual for Object Oriented Programming 1 at The Hashemite University, containing various worksheets with programming exercises in Java. It covers topics such as input/output, selection statements, repetition statements, methods, arrays, and classes, with specific tasks for students to complete. Each worksheet includes multiple questions that require writing Java programs to solve problems related to the concepts taught in the course.

Uploaded by

saifalhomimat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

The Hashemite University

Prince Al-Hussein bin Abdullah II Faculty for Information Technology

Object Oriented Programming 1


Lab Manual

2020, Sep
Page
Worksheet One: Working with Java

Question#1 (Output)
Write a program to print the following message "Welcome to Java class".

Question#2 (Swap)
Consider the following two variables:
int x=10;
int y=50;
Write a program to print the values of x and y, then swap the two values using a third variable,
then, reprint the new values of x and y.

Question #3 (Precedence Rules)


Write a program to calculate and print the result of the equation below, consider the following
variables:
int x=1; int y=1;
int a=1; int b=1; int c =1;

3 + 4x 10( y − 5)(a + b + c) 4 9+ x
− + 9( + )
5 x x y
Question #4 (Digits)
Assume that
int x= 123;
Write a program that calculates and prints the sum of all digits in a 3-digits number. Assume int
x =123 is our number.

For example, x=123, the sum of all its digits is 1+2+3 =6.

(Hint): Use the % operator to extract digits, and use the / operator to remove the extracted digit.
For instance, 123 % 10 = 3 and 123 / 10 = 12

2
Page
Worksheet Two: Introduction to Java (Input/Output)

Question#1 (Using Console)


Write a program that reads the marks of three students from the console, then calculates and
displays their average using the console too.
Hint: use the following piece of code:
Scanner s = new Scanner (System.in);
int h=s.nextInt();

Do not forget to import java.util.Scanner;


Question #2 (Reading characters):
Write a program that reads any character using the console then prints the corresponding Ascii code. For
example, if the user enters 'a', the output will be 97.

Rewrite the program using Dialog Boxes.

Question #3 (Using Dialog Boxes)


Write a program that reads a Fahrenheit degree in double from an input dialog box, then converts
it to Celsius and displays the result in a message dialog box.
Hint: celsius = (5/9) * (fahrenheit - 32), use the following piece of code:

String s = JOptionPane.showInputDialog(null,"Enter the Fahrenheit


degree");
double fahrenheit =Double.parseDouble(s);

Do not forget to import javax.swing.JOptionPane ;


Rewrite the program using console.

Question #4 (Math Class):


Write a program that reads the radius of a circle using dialog boxes then calculates and displays
its area.
Hint : cir _area =PI*radius^2, use Math.PI constant and Math.pow(double,double) method.

Rewrite the program using console.


3
Page
Worksheet Three: Selection Statements

Question #1 (if/else)
Write a program that reads a student mark in double and prints pass if mark is greater than or equal
50 otherwise prints fail.

Question #2 (nested If/else )


Write a program that reads an integer number and prints if it is an odd or even number, positive or
negative number.

Question #3 (Conjunction Operators)


Write a program that reads an integer number and determines whether it is divisible by both 5 and 6,
whether it is divisible by either 5 or 6, and whether it is divisible by either 5 or 6 but not both.
Hint: Use the (&&, || and ^ operators).

Question #4 (Salary):
Write a program that reads the basic salary in double (using dialog boxes). The program should
calculate the net salary according to the formula:
Net_salary= basic_salary – basic_salary*tax
- Tax equals 0.18 if the basic salary is greater than 1000.
- Tax equals 0.12 if the basic between 500 and 1000.
- Otherwise tax equals 0.08
The net salary should be displayed in message dialog box with no icon and the title should be "Net
Salary".

Question #5 (Switch)
Write a program that reads two integers and a mathematical operation character (+,-,*,/) then
find the proper result (Hint: use switch statement and dialogboxes). For instance, if user entered
3, 2 and '+' the result should be (5).

Question #6 (Rewrite if into switch)


Rewrite the following if statement into switch statement. Initialize x to 0 and a to 3, and display
the value of x after executing the switch statement.
if (a == 1)
x += 5;
else if (a == 2)
x += 10;
else if (a == 3)
x += 16;
else if (a == 4)
4

x += 34;
Page
Worksheet Four: Repetition Statements

Part One: Counter controlled loops

Question #1 (loops forms):


Write a program to find and print the sum of all numbers between 1 and 1000 using:
• For loop
• While loop
• Do/while loop

Question #2 (Evens and Odds):


Write a program to print the even numbers between 1 and 50 on a massage dialog box, and odd numbers
on another one.

Question #3 (Divisibility):
Write a program that reads in two integers and displays all numbers that are odd and divisible by 5.
Consider all cases (i.e. num1> num2 or num1<num2)

Question #4 (Series):
Write a java program to calculate and print the value of the following series.
1+8+27+………… + N3.

Question #5 (Factorial):
Write a program that reads in an integer, then calculates and prints its factorial.
(Hint: 4! =4*3*2*1 =24)

Question #6 (Prime):
Write a program that reads in an integer and indicates whether this it is Prime or not.

Part Two: Sentinel controlled loops

Question #7 (Average):
Write a program that reads in unspecified number of marks for students, the program should calculate
and print the average of all entered marks when the user enters any negative value.

Part Three: Nested loops

Question #8 (Shapes):
Write a program to print the following:
5
Page
1
22
333
4444

Question #9 (Primes) :
Update the program in question 6 to print all the prime numbers from 1 to 100.

6
Page
Worksheet Five: Working with Methods

Question One (Grades):


1. Write a method getGrade that takes the mark as double and returns:
• A: (90<=mark <=100)
• B: (80<=mark <90)
• C: (70<=mark <80)
• D: (60<=mark <70)
• E: (50<=mark <60)
• F: otherwise
❖ Hint: use switch statement.

2. Write a method calculateAverage that takes the sum of marks as double, their number as integer
and returns the average of marks.

3. Write a method getResult that takes the average of marks as double and returns "PASS" if the
average is greater than or equal 50 and "FAIL" otherwise.

4. Write a method printResult that takes the average of marks as double and outputs the statement
"Congratulations!!! You Passed!!!" if the result is "PASS", and the statement "Sorry!!! You
Failed!!!" if the result is "Fail".
❖ Hint: use the getResult method with the equals or equalsIgnoreCase Method.

5. Implement the main() method as follows:


a) Input the unspecified number of marks for a student.
❖ Hint: use a negative value to exit the loop.
b) Output the grade for each mark.
❖ Hint: call the getGrade method.
c) Output the average of the marks of the student.
❖ Hint: call the calculateAverage method.
d) Output the final result of the student.
❖ Hint: call the getResult method.
e) Output the result statement.
❖ Hint: call the printResult method.
7
Page
Question One (Random):

1. Write a method calculateRightAnswer that takes two integers and returns their summation.
2. Write a method checkAnswer that takes three integers. The method should check whether
the summation of the first two integers equals the third. If so, the method should return
(true), otherwise, the method should return (false).
❖ Hint: use the calculateRightAnswer method.
3. Implement the main() method as follows:
a. Generate two integer values randomly in the range [1-10].
b. Input the guessed user answer using Input Dialog:
• Message: "What is the result of "+ r1 + " + "+ r2+"???!!!! "
• Title: "Guess??!!!"
• Icon: QUESTION_MESSAGE
c. Check whether the sum of the two generated numbers equals the number
entered by the user.
❖ Hint: Call the checkAnswer method.
▪ If so, display a Message Dialog
• Message: "WOW!!! Right!!!"
• Title: "Result"
• Icon: "INFORMATION_MESSAGE"
▪ Otherwise, display a Message Dialog
• Message: "Sorry!!! Wrong"
• Title: "Result"
• Icon: "ERROR_MESSAGE"

8
Page
Worksheet Six: Working with One-dimensional Arrays

Question#1 (Marks)
Write a Java application that uses one dimensional array to do the following:
a) Inputs the number of marks (i.e. array size) from the user
b) Inputs the marks of a student into the array
c) Prints the marks of the student
d) Calculates and displays the average of marks
e) Finds out the number of marks that are above the average
f) Write a method that finds and returns the minimum mark
g) Write a method that finds and returns the maximum mark
h) In the main(), display the minimum and the maximum mark
i) Rewrite the program using dialog boxes.

Question#2 (Even_Odd)
Write a java program that :

a) Define a method called sumOfGreaters (int [], int) that finds the sum of all elements that
is greater than second parameter.

b) Define a method called FillEven(int[],char []) that checks whether each number in the
integer array is even or odd and fills the corresponding position of the character with
either 'E' or 'O'.

Example:
If the user entered 15 - 24 the number array is:
15 16 17 18 19 20 21 22 23 24
The Even array must be as:
O E O E O E O E O E

c) In the main():
a. Prompt the user to input two integer’s num1 and num2 and define an integer
array called "numbers" that contains numbers from num1 to num2.
b. Prompt the user to input an integer and output the sum of all array elements that
are greater that integer.
c. Create a character array and fill it with either 'E' or 'O' using the already defined
method.
9
Page
Worksheet Seven: Working with Two-dimensional Arrays

Question#1 (Marks)
a) In the main(), create and initialize the following two-dimensional array, name it "array".
1 2 3 4
7 8 2 2
9 8 7 6
1 0 1 2

b) Define the method named getSumOfArray(int [][] a) that calculates and returns the sum of all
elements of the array.
c) Define the method named getSumofRow3 (int [][] a) that calculates and returns the sum of the
third row of the array.
d) Define the method named getSumofCol3 (int [][] a) that calculates and returns the sum of the
third column of the array.
e) Define the method named getSumofDiagonal (int [][] a) that calculates and returns the sum of the
primary diagonal of the array.
f) Define the method named printRowsSum (int [][] a) that calculates and prints the sum of each
row of the array.
g) Define the method named printColsSum (int [][] a) that calculates and prints the sum of each
column of the array.

Question Two (ASCII):


a) Create an integer two-dimensional array named "ascii"; the dimensions of this array should be
entered by the user.
b) Define the method fillAsciiArray (int [][]ascii) that fills the ascii array with random integer values
between 65 and 100.
c) Define the method fillLettersArray (int [][]ascii) that creates a character array "letters" of the same
size of the integer array, and fills it with the letter that corresponds to the ascii code in the
corresponding position in the ascii array. The method should return the letters array.
d) In the main():
a. Print out ascii array in a tabular format. (Hint: the dimensions should be entered by the
user).
b. Print out the letters array in a tabular format.
10
Page
Worksheet Eight: Working with Classes

Question#1 (Constructors):
1. Create a class called Rectangle that contains the following data fields:
• height as integer.
• width as integer.
2. The class also contains the following methods:
• A no-arguments constructor that initializes Rectangle data fields to their default values.
• A two-arguments constructor that initializes Rectangle data fields to specific given values.
• A method named getArea() that returns the area of the rectangle.

3. In the main method:


• Create an object (r1) with its default values
• Create an object (r2) of the Rectangle class with width=10 and height =20.
• Print the area of the rectangle r1 by invoking getArea().

Question#2 (Access Modifies, Mutators and Accessors):


1. Create a class called Student that contains the following data fields:
• name as private String.
• stdno as private integer.
• grade as private integer.
2. The class also contains the following methods:
• A no-argument constructor to initialize the Student data fields to its default values.
• Set and get methods for all data fields.
o setGrade method will check if the grade is less than 40 it will be set to 40,
otherwise the grade will be the same.
• classifyGrade method that has no argument and returns the appropriate letter for the
grade according to the following:
80 - 100 --------- A
50 – 79 ---------- B
< 50 -------------- F
• print method that prints the Student data fields and the grade letter (invoke classifyGrade
method).
3. In the main method :
• Create an object (s1) of the Student class with name ="Ahmad", ID= 123415, grade=85
• Invoke classifyGrade method and print the corresponding grade letter for s1.
• Print all student information.
11
Page
Question#3 (Instance variables and static variables):
1. Create a class called Account that contains the following data fields:
• num as a static private integer
• id as private integer.
• balance as private double.
2. The class also contains the following methods:
• A no-arguments constructor that
o initializes data fields to their default values
o increments num and assigns the new num to the id.
• The set and get methods for id and balance data fields.
• Static set and get method for num data field.
• A method called withdraw(double) that withdraws a specified amount from the account
balance. Before withdraw, the method should check whether the available balance is
sufficient.
• A method named deposit(double) that deposits a specified amount to the account
balance.
3. In the main method :
• Create an object (a1) of the Account class with balance=1000.
• Create an object (a2) of the Account class with balance=2000.
• Print id and balance of a1 and a2.
• Withdraw 100 from a1 balance.
• Deposit 50 to a1 balance.
• Print the balance of a1 and a2.
• Print the total number of the created accounts

12
Page
Worksheet Nine: Working with String Methods

Basic String Methods API

• int length(): It returns the length of a String.


• String toUpperCase(): Converts the string to upper case string using the rules defined by specified
locale.
• boolean equals(Object obj): Compares the string with the specified string and returns true if both
matches else false.
• boolean equalsIgnoreCase(String string): It works same as equals method but it doesn’t consider the
case while comparing strings. It does a case insensitive comparison.
• char charAt(int index): It returns the character at the specified index. Specified index value should be
between 0 to length() -1 both inclusive. It throws IndexOutOfBoundsException if index<0||>= length
of String.
• int indexOf(int ch): Same as indexOf method however it starts searching in the string from the
specified fromIndex.
• String substring(int beginIndex): It returns the substring of the string. The substring starts with the
character at the specified index.
• String substring(int beginIndex, int endIndex): Returns the substring. The substring starts with
character at beginIndex and ends with the character at endIndex.
• String replace(char oldChar, char newChar): It returns the new updated string after changing all the
occurrences of oldChar with the newChar.
• boolean contains(CharSequence s): It checks whether the string contains the specified sequence of
char values. If yes then it returns true else false. It throws NullPointerException of ‘s’ is null.
• public boolean isEmpty(): This method returns true if the given string has 0 length. If the length of the
specified Java String is non-zero then it returns false.
• String[] split(String regex): It splits the string and returns the array of substrings that matches the given
regular expression.

13
Page
Question#1 (using String Methods):
Create a Java application (Q1).
• The application should repeatedly ask the user to enter a word (using input box) until the user
enters the word “stop”. When the user enters “stop”:
• The number of words that contains the letter “m” will be displayed on a message box.
• The number of letters in the shortest word will be displayed on a message box.

Question#2 (Array of Strings):


Create a Java application (Q2).

• The application should ask the user to enter sequence of nouns in the console separated by either
commas or spaces. The application should read the sequence of nouns as line.
• Create a String array (nouns) that contains the nouns in the line.
• Create a Boolean array (isVowel) with the same length as nouns.
• Create a String array (articles) with the same length as nouns
• Fill the array isVowel with true if the first character of each noun in the corresponding position in
the array nouns is a Vowel (capital or small), otherwise fill that position with false.
• Fill the array articles with “An” if the first character of each noun in the corresponding position in
the array nouns is a Vowel, otherwise fill that position with “A”.
• Print the elements in the three arrays in a tabular format.

14
Page
Worksheet Ten: Working with Files

Question#1 “Writing to Files”


Write a Java application that writes your name, your ID, and your major to a file named “myfile.txt”

Question#2 “Reading from Files”


Write a Java application that read the content of a text file line by line and display it on the Console.

Question#3 “Copy File Content”


Write a Java application that copy the content of a text file into another text file.

Question#4 “Comma-separated file”


A student text file has the following structure “FirstName,MiddleName,LastName,Mark”.

Write a Java code that:

a) Writes the firstName and the lastName of each students in a new text file.
b) Counts the number of students and displays it on the console.
c) Finds the maximum mark and displays it on the console.

15
Page

You might also like