Sie sind auf Seite 1von 58

Al Imam Mohammad Ibn Saud Islamic University

College of Computer and Information Sciences


Computer Science Department

Lab Manual

CS 150 Introduction to Computer

Programming and

CS 140 Computer Programming I

Page 1 of 44

Imam University | CCIS | Doc. No. 006-01-


20141026
Table of Contents

Note to students.......................................................................................................5
Lab 0 – Introducing the Work Environment...........................................................6
1.1. Lab Goals.....................................................................................................6
1.2. Installing Visual Studio Code (VS Code) with Java Extension...................6
1.2.1. Installing VS Code........................................................................6
1.2.2. Installing Java Installer...............................................................8
1.2.3. Install Live Share........................................................................11
1.3. Exercise 1: Edit, compile and run a Java program....................................12
1.4. Exercise 2: Output.....................................................................................14
1.5. Exercise 3: Indentation.............................................................................14
1.6. Exercise 4: Exploring syntax errors..........................................................15
1.7. Exercise 5: Syntax errors...........................................................................15
1.8. Exercise 6: Output 2..................................................................................16
1.9. Exercise 7: Print a shape...........................................................................16
Lab 1 – Java Fundamentals................................................................................17
1.1. Lab Goals...................................................................................................17
1.2. Exercise 1.....................................................................................17
1.3. Exercise 2..................................................................................................18
1.4. Exercise 3...................................................................................................19
1.5. Exercise 4...................................................................................................19
1.6. Exercise 5..................................................................................................20
Lab 2 – Selection Control Statements (Part 1)........................................................21
2.1. Lab Goals...................................................................................................21
2.2. Exercise 1........................................................................................21
2.3. Exercise 2...................................................................................................21
2.4. Exercise 3..................................................................................................22
2.5. Exercise 4..................................................................................................22
2.6. Exercise 5..................................................................................................22
1. 2.6. Exercise 6............................................................................................22
Lab 3 – Selection Control Statements (Part 2).......................................................23
3.1. Lab Goals...................................................................................................23
3.2. Exercise 1..............................................................................................23
3.3. Exercise 2..................................................................................................23

Page 2 of 44
3.4. Exercise 3..................................................................................................24
3.5. Exercise 4..................................................................................................25
3.6. Exercise 5 (Homework)............................................................................26
Lab 4 – Repetition Control Statements (Part 1).....................................................27
4.1. Lab Goals...................................................................................................27
4.2. Exercise 1...............................................................................................27
4.3. Exercise 2..................................................................................................27
4.4. Exercise 3..................................................................................................27
4.5. Exercise 4..................................................................................................27
4.6. Exercise 5..................................................................................................27
4.7. Exercise 6 (Homework).............................................................................27
Lab 5 – Repetition Control Statements (Part 2).....................................................29
5.1. Lab Goals..................................................................................................30
5.2. Exercise 1..............................................................................................30
5.3. Exercise 2..................................................................................................30
5.4. Exercise 3..................................................................................................30
5.5. Exercise 4...................................................................................................31
5.6. Exercise 5 (Homework)............................................................................32
Lab 6 – Methods (Part 1)........................................................................................33
6.1. Lab Goals...................................................................................................33
6.2. Exercise 1..............................................................................................33
6.3. Exercise 2..................................................................................................34
6.4. Exercise 3..................................................................................................34
6.5. Exercise 4 (Homework)............................................................................34
Lab 7 – Methods (Part 2)........................................................................................35
7.0. Lab Goals...................................................................................................35
7.1. Exercise 1..............................................................................................35
7.2. Exercise 2..................................................................................................36
7.3. Exercise 3..................................................................................................36
7.4. Exercise 4..................................................................................................37
Lab 8 – Arrays (Part 1)........................................................................................38
8.0. Lab Goals..................................................................................................38
8.1. Exercise 1..............................................................................................38
8.2. Exercise 2..................................................................................................38
8.3. Exercise 3..................................................................................................38

Page 3 of 44
8.4. Exercise 4.................................................................................................38
Lab 9 – Arrays (Part 2)...........................................................................................40
9.1. Lab Goals..................................................................................................40
9.2. Exercise 1..............................................................................................40
9.3. Exercise 2..................................................................................................40
9.4. Exercise 3..................................................................................................40
Lab 10 – Strings......................................................................................................41
10.1. Lab Goals.................................................................................................41
10.2. Exercise 1......................................................................................41
10.3. Exercise 2................................................................................................42
Lab 11 – Files......................................................................................................43
10.1. Lab Goals................................................................................................43
10.2. Exercise 1............................................................................................43
10.3. Exercise 2................................................................................................44

Page 4 of 44
Note to students
This lab manual is prepared for laboratory sessions of the courses CS 150 – Introduction to
Computer Programming CS140 – Computer Programming 1.

To take benefit from laboratory sessions, students must work continuously and must feel
committed to the course during the whole semester. To do so, students have to:

 Before the lab: Review the course, review the tutorial exercise model answers, read,
understand, and, eventually, start answering the lab questions.
 During the lab:
o Create a folder for each lab and place all the class files inside it.
o Read the question, analyze the requirements, design the solution, write the
answer, then test the answer with different values.
o Ask the TA if there is difficulty to understand a question.
o Talk to each other for help.
 After the lab: if students didn’t finish answering all the exercises, they have to keep
working on them as homework.

Each lab in this manual is intended to be done in one lab session (2 hours). After the end of
each lab session, the course instructor or the teaching assistant provides a soft copy of the
detailed solution of the exercises to students.

We are happy to have you among our students and we wish you a successful course with an
excellent level of learning and practicing.

Page 5 of 44
Lab 0 – Introducing the Work Environment
1.1. Lab Goals

 Learn how to install VS Code and Java Installer


 Learn the basic commands and tools to edit, compile, and execute a Java program
 Learn how to use the environment collaboratively.
 Be familiar with the Java program structure.
 Get introduced to syntax errors in Java.
 Write simple output programs.

1.2. Installing Visual Studio Code (VS Code) with Java Extension

01.1 Installing VS Code IDE

1. Go to the following link https://code.visualstudio.com/download


2. Choose your operating system (Windows or MacOS) to download the installation file.

Page 6 of 44
3. For example on Windows you will download the following installation file. (MacOS
instructions are similar)

4. Follow the instructions, click “Next” (generally use the default settings).

5. Continue to click “Next” until the installation is complete as shown below then
click “Finish”.

Page 7 of 44
For more details on installation:
 Windows https://code.visualstudio.com/docs/setup/windows
 MaxOS https://code.visualstudio.com/docs/setup/mac

6. Launch VS Code, the application window is shown below (this is on MacOS) Windows is
similar.

Page 8 of 44
1.1.2 Installing Java Extension

1. [Very Important] First make sure you have the java development kit (JDK) installed, if
you have not installed it you can install it from this link. (Currently JDK 14 is the latest
version)
https://www.oracle.com/java/technologies/javase-jdk14-downloads.html

2. After installing JDK, you need to install the Java Installer for VS Code, so go to this link
https://code.visualstudio.com/docs/languages/java

3. You will find two links, as shown above select the one according to your
operating system.
4. The installer will be downloaded to your system.
5. Save installer, the open it and follow the instructions

Page 9 of 44
You have now finished installing the Java Installer. You can go to step 0.2 to write your first
java program and test your installation.

1.1.3 Installing Live Share

Live share is a collaborative coding environment. It will be very useful in the classroom and
lab sessions. You can install it from this link.

https://visualstudio.microsoft.com/services/live-share/

Page 10 of 44
For more details on how to use Live Share, please refer to
https://docs.microsoft.com/en-us/visualstudio/liveshare/use/vscode

Page 11 of 44
1.3. Exercise 1: Edit, compile and run a Java program
1. Choose a location on your computer and create a folder name it “Programming” (You can
use any name you like).
2. On VS Code, go to the menu
File -> Open… -> [Select the folder “Programming” you created above]

3. Click Open (Your application window should be similar to the one below)

4. Click on Programming Folder, then go to the “open file” icon and select it.

5. Type in the name of the file it must be “Hello.java”, then press “Enter”.
6. The application will look like the figure below:

Page 12 of 44
7. Type in the following code into the file.

8. Go to the Menu, Select Run -> Start Debugging


9. The program output will appear in the terminal

Page 13 of 44
Congratulations on your first program !
0.3 Exercise 2: Output ‫يبي االوت بوت‬
Write, save, compile, and run the following HelloWorld2. Analyze and comment what the
program does.
public class HelloWorld2
{
public static void main(String[] args)
{
System.out.print("Hello ");
System.out.println("World");
}

1.4.Exercise 3: Indentation ‫المسافة البادئة‬


The indentation make the program clear and easy to read. The following program is not
properly indented, paste it into VS Code and fix the indentation. ‫يقول المسافة البادئة‬
‫تجعل البرنامج اسهل للقراءة وهنا مركبها على بعضها‬
public class FixIndent {
public static void main(String[] args) {
System.out.println("First line");
System.out.println("Second line");
System.out.println("Third line");
System.out.println("Forth line");

}}
1.5. Exercise 4: Exploring syntax errors ‫اكتشاف األخطاء‬
This exercise makes you familiar with the error messages produced by the compiler.
Open the file HelloWorld.java used in the Exercise 1, then perform the following
modifications, compile and run your program every at every change. Try to read and
understand the error messages.

 Modify the class name.


 Remove a { brace
 Remove a } brace
 Remove the word void
 Remove a dot.
 Remove a semi-column (;)
 Remove one quotation (")
 Replace public with Public
 Add a ( parenthesis.

1.6. Exercise 5: Syntax errors ‫أخطاء فقط‬


The following program contains 6 errors.
public class FixSyntax
public static void main(String[] args)
{
System.out.printLn("First");
System.out.println("Second")
System.out.println(Third);
System.out.println("Forth";
System.println("Fifth");
}
}
Try to identify the errors, then create and test a corrected version of this program.

Page 15 of 44

Imam University | CCIS | Doc. No. 006-02-


20170316
1.7. Exercise 6: Output 2 ‫يبي االوت بوت‬
What does the following program print out?
public class Output {
public static void main(String[] args) {
System.out.print("Learn\tJava\n\tthe\nHard\tWay\n\n");
System.out.print("\tLearn Java the \"Hard\" Way!\n");

System.out.print("Hello\n");
System.out.print("Jellow\rY\n");

System.out.println("\\ // -=- \\ //");


System.out.println("\\\\ \\\\\\ \\\\\\\\");
}
}

1.8.
Exercise 7:
Print a shape ‫طباعة شكل‬
Consider the following program:
public class Square
{
public static void main(String[] args)
{
System.out.println " "
( ********* );
System.out.println " * "
( );
*
System.out.println " * "
( );
*
System.out.println " * "
( );
*
System.out.println " * "
( );
*
System.out.println " * "
( );
*
System.out.println " * "
( );
*
System.out.println " * "
( );
*
System.out.println " "
( ********* );
}
}

Lab 1 – Java Fundamentals

1.1. Lab Goals


 Display text with print, println, printf, escape character (/), and
format specifiers
 Declare, initialize (assignment operator), print variables of different types (int,
double, boolean, char, and String)
 Write/evaluate expressions using arithmetic operations (+, -, *, /, %) by
considering the precedence rules arithmetic operators
 Obtaining variables values as input from the user using Scanner methods
(nextInt, nextDouble, next, nextLine, next().charAt(0))
 Write expressions using abbreviate operators (++, --, +=, -=, *=. /=, %=)

1.2. Exercise 1
Write and run the following program, then check what it does print out.‫بوت‬ ‫يبي االوت‬
public class Variables {
public static void main(String[] args)
{ int i = 7;
double Pi = 3.14;
boolean boolValue = true;
char character = 'a';
String s = "Hello!";

System.out.println(i);
System.out.println(Pi);
System.out.println(boolValue);
System.out.println(character);
System.out.println(s);
}
}
format specifier type of argument to be formatted
%c character
%d decimal integer (base 10)
%f floating-point number
%b boolean
%s a string of characters
%n Move the cursor to a new line
Example:
System.out.printf("the %s jumped over the %s, %d times", "cow", "moon", 2);
Will print: the cow jumped over the moon, 2 times

1.3. Exercise 2

Create a Java program that declares four variables and asks the user to input their
values. These variables will contain: ‫ متغيرات والمستخدم يدخلها الحل تحت‬4 ‫يبغاني اعرف‬

 your big brother name


 your big brother age
 your small brother name
 your small brother age

Then produce output in this format using your four variables:

Your big brother Anes (25 years) is 9 years older than


your small brother Rakan (16 years).

For this exercise, you have to declare a Scanner (input) to enter these 4 variables.
According to the type of your variable, choose the appropriate input method from the
following table:

code (calling method of the Scanner Class) description

int n = input.nextInt(); Read an integer


double d = input.nextDouble(); Read a double
String s = input.next(); Read a string with no
spaces String s = input.nextLine(); Read a string with spaces
char c = input.next().charAt(0); Read a character

Page 18 of 44
Exercise 3
Evaluate the results of each of the following expressions, then check you answer using a Java
program.‫طلعي كل نتيجة من كل العمليات وتأكدي حلك عن طريق الكود‬

1-12 / 5 + 8 / 4
2-3 * 4 + 15 / 2
2- -(1 + 2 * 3 + (1 + 2) * 3)
3- 42 % 5 + 16 % 3
4- 5 * 6 / 4 % 3 - 23 / (14 % 6)
5- 30 % 9 + 5 % 8 - 11 % 4 % 2
6- 1 + 9 / 2 * 2.0
7- 2.5 * 2 + 17 / 4
8- 4.5 / 3 / 2 + 1
9- 46 / 3 / 2.0 / 3 * 4/5
10- 50 / 9 / 2.0 + 200 / 10 / (5.0 / 2)
Exercise 4
Each of the following program fragments contains 2 errors.

Fragment 1:‫األخطاء‬ ‫طلعي‬


‫احط عالمة زائد بين النص واالكس‬
int x = 5;
‫االكس ما عطيتها قيمه‬
System.out.println("x is" + x);
Fragment 2:
‫( العدد حاط فاصله مو نقطه بوينت هذا غلط نحط‬.)
double z = 5,2;
int y = z * z; ‫نغير االنتجر نحطه دبل‬
Fragment 3:
boolean bool = "true"; ‫)’ ’( الكاركتر المفروض كذا‬
char character = "Z"; ‫)""( البولين نحذف ال‬
Fragment 4:
int c, a = 1, b = 2; A++2 must be a=+2
c = a++2 + ++b; =% must be %=
c =% 2;

Try to identify the errors, then create and test a corrected version of each fragment
independently.

Exercise 5
Write a Java application that displays a square, a triangle, and a diamond using
asterisks (*), as follows: ‫ سهل طباعة اشكال‬,,, System.out.println

******* * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *
******* ************* *
Lab 2 – Selection Control Statements (Part 1)
2.1. Lab Goals
 Solve problems using if; single-selection statement
 Solve problems using if…else; double-selection statement
 Solve problems using nested if…else.
 Use of equality and relational operators
 Use of conditional operator (?:)

2.2. Exercise 1

Identify and correct the errors in each of the following statements: ‫اكتشاف األخطاء‬

a) if ( c < 7 );
System.out.println( "c is less than 7" );

b) if ( c => 7 )
System.out.println( "c is equal to or greater than 7" );

You can put the code in the editor, then compile and try to find and resolve the errors
(declare c as integer and give it an arbitrary value).‫عرفي السي وعطيها قيمه اوليه‬

2.3. Exercise 2

What does the following program print out? ‫يبي االوت بوت‬

public static void main(String[] args)


{
char x = 'N'; if (x == 'Y') {
if (x == 'N')
System.out.printf("inside if\n");
else
System.out.printf(“inside if else\n”);
} else {
System.out.printf("inside else\n");
}
}
2.4. Exercise 3

Write a Java program that computes the minimum of 3 numbers entered by the user.‫نستخدم السكانر هنا‬

2.5. Exercise 4
Write a Java program that determines whether a number n given by the user is a even
(multiple of 2) or odd (not multiple of 2).‫هل القيمة زوجية او فردية ؟‬
Hint: Use the modulus (%) operator to determine whether a number is multiple to
another. ‫ هو زوجي‬0 ‫ يساوي‬2 ‫اذا باقي القسمة على‬
2.6. Exercise 5
Write a Java program that computes the absolute value of the product of 2 numbers
given by the user. Use if/else or the ternary conditional operator (? :) to make
decision.‫يحسب القيمة المطلقة لرقمين مدخلين من قبل المس~~تخدم نس~~تخدم ش~~رط اف ايلس او‬

‫العالمة المعطاة (بديله ل اف ايلس) ل اتخاذ قرار‬


Exercise 6
Write a Java program that receive a number between 1 and 7, and prints the day corresponding
to the entered number starting by Friday. When the use enters a value that doesn’t correspond to
any day (less than 1 or more that 7), the program displays an error message.‫اكتب كود يستقبل رقم‬

‫بين الواحد والسبعة بعدين يطبع اليوم المقابل لهذا العدد المدخل ابتداء من الجمعة‬
Lab 3 – Selection Control Statements (Part 2)

3.1. Lab Goals


 Solve problems using if, if/else, and nested if and if…else.
 Solve problems using switch; multiple-selection statement
 Use of equality and relational operators
 Use of logical operators

3.2. Exercise 1
Consider the following code fragments.‫يبي االوت بوت‬

if (x != 0 && y % x == 0)
System.out.printf("%d multiple of %d\n", y, x);

if (x > 0 || y++ > x)


System.out.printf("%d is also positive\n", y);

Answer the following questions:


1) What is the output when x = 5 and y = 25  ‫يطبع الشرطين‬
2) What is the output when x = 0 and y = 6  7 ‫بيطبع الرقم‬
3) What is the output when x = -2 and y = -8  2- ‫ من مضاعفات‬8- ‫بيقول ال‬
4) What is the output when x = 0 and y = 0 
5) If we inverse the two conditions of the first if statement‫ لو عكسنا الشرطين في االف األولى وش تصير ؟‬:
if ( y % x == 0 && x != 0))
It will result the same output when x = 0 and y = 6?‫خطأ منطقي‬
6) Explain why if the first condition of the second if statement is true, y is
not incremented

3.3. Exercise 2
Using the switch statement, rewrite the solution of the exercise 6 from the previous lab
(Lab 2).
3.4. Exercise 3
Write a Java program that performs the following tasks:

 Ask the user to input the lengths of the three sides of a triangle (three double
variables). ‫ اضالع للمثلث‬3 ‫ اطوال نوعه دبل تمثل‬3 ‫اسأل المستخدم يدخل‬

 Determine and print the type of the triangle: regular (all three sides are
equal), symmetric (only two sides are equal), or irregular (all sides are
different).‫حددي واطبعي نوع المثلث فيه شرط‬

 In all cases, compute and display the perimeter of the triangle (the sum of all sides). ‫في كل الحاالت اطبعي‬
‫واعرضي محيط المثلث اللي هو مجموع االضالع الثالث للمثلث‬
Example 1:
Enter triangle sides: 5.2 5.2 5.2

The triangle is regular.


Its perimeter is: 15.600000.

Example 2:
Enter triangle sides: 3.4 6.9 3.4

The triangle is symmetric.


Its perimeter is: 13.700000.

Example 3:
Enter triangle sides: 2.3 5.0 4.1

The triangle is irregular.


Its perimeter is: 11.400000.
3.5. Exercise 4

Write a Java program that simulates withdrawal bank operations. The program will perform
the following tasks:

 Declare the amount variable and initialize it with the value 5000.
 Ask the depositor to enter the amount to withdraw
 Accept only the amounts less than the amount value (5000) and multiple of 50
 Compute and print the minimum number of banknotes required to represent
the given withdrawal amount, knowing that only 3 types of banknotes can be
provided: 50, 100, and 500.
 Compute and print the new amount after withdrawal.

Example 1:
Enter withdrawal amount: 5670
You must enter an amount multiple of 50 and less than 5000.

Example 2:
Enter withdrawal amount: 45670
You must enter an amount multiple of 50 and less than 5000.

Example 3:
Enter withdrawal amount: 2750
- 500 * 5
- 100 * 2
- 50 * 1
You got 8 banknotes.
Remaining amount is 2250.

Example 4:
Enter withdrawal amount: 4500
- 500 * 9
You got 9 banknotes.
Remaining amount is 500.

Page 25 of 44
3.6. Exercise 5 (Homework)
Write a Java program that allows a driver to determine the cost of an automobile insurance.
Your program has to:

 Ask the driver to input his/her age and the number of accidents that the driver has had.

 Compute and print the total cost based on:

o Basic charge is $550

o Surcharge of $100 if the driver under 25

o Additional surcharge for the number of accidents:

Number of Accident
accidents Surcharge
1 50
2 125
3 225
4 375
5 575
6 or more No insurance

Example 1:
How old are you? 45
How many accidents you had before? 6

Sorry, No insurance

Example 2:
How old are you? 20
How many accidents you had before? 3

Your insurance cost is 825

Example 3:
How old are you? 30
How many accidents you had before? 3

Your insurance cost is 725

Page 26 of 44
Lab 4 – Repetition Control Statements (Part 1)

4.1. Lab Goals


 Solve problems using while, repetition control statement
o Counter-controlled repetition
o Sentinel-controlled repetition
 Solve problems using nested control statement

4.2. Exercise 1
Write a Java program that computes the factorial of a number n given by the user
(n! = n * n-1 * … * 2 * 1). ‫اكتب كود يوجد المضروب بإستخدام اللوب والزم اعطيه قيمة‬

‫ابتدائية‬

4.3. Exercise 2
Write a Java program that computes the sum of even numbers that are in the range
[a, b] where a and b are given by the user (without nesting the control statements).
4.4. Exercise 3
Write a Java program that computes nth term of the following sequence:
U0 = 1; U1 = 2; Un+2 = 2*Un+1 + Un + 1.

4.5. Exercise 4
Write a Java program that computes the second maximum of n numbers given by the
user (use sentinel approach).

Page 27 of 44
4.6. Exercise 5

Write a Java program to compute the value of π, using the following series expansion.

Your program asks the user to enter a value between 921 and 10000000 that represents
the max value of the denominator.

At the end, your program prints the computed value of PI and the different between
Math.PI and the computed value.

Hints: Add a number to sum if the denominator modulus 4 is 1, and subtract from sum
if it is 3.

Example 1:

Enter max value for dominator (921 - 10000000): 950

Computed = 3.1436979144150006
PI
Math.PI = 3.141592653589793
Differenc = -
e 0.002105260825207455
6
Example 2:

Enter max value for dominator (921 - 10000000): 200

Invalid value, good bye.


Page 28 of 44
4.7. Exercise 6 (Homework)

Write a complete Java application that implements the Number Guessing Game.
Your application declares a variable and assign to it a predefined value (e.g. 70), and
then it asks the player (user) to enter a guess (number) between 0 and 1000 or -1 to
exit the game. Each time the player enters a guess, the computer tells him whether the
guess is too high, too low, or right. Once the player guesses the number or wants to
exits, the game is over, and prints the number of trials.

Example 1:
Enter your guess (0-1000 or -1 to exit): 30
It is too low
Enter your guess (0-1000 or -1 to exit): 100
It is too high
Enter your guess (0-1000 or -1 to exit): 70

CONGRATULATIONS! ... You win after 3 guess(es).

Example 2:
Enter your guess (0-1000 or -1 to exit): 50
It is too low
Enter your guess (0-1000 or -1 to exit): 1100
Your guess must be between 0 and 1000
Enter your guess (0-1000 or -1 to exit): -1

You abandoned the game! ... You guessed 1 time(s).

Page 29 of 44
Lab 5 – Repetition Control Statements (Part 2)

5.1. Lab Goals


 Solve problems using for and do/while, repetition control statement
 Solve problems using nested control statement
 Use of break and continue statements

5.2. Exercise 1
Write a Java program that determines the set of divisors of a number n given by the
user.

5.3. Exercise 2
Write a Java program that computes the greatest common divisor (GCD) of two
numbers n and p given by the user.

5.4. Exercise 3
Write a Java program that calculate the number of lowercase characters and the
number of uppercase characters in a sequence of characters entered by the user. When
the user wants to stop entering characters, he will enter the character ‘#’ (use switch).

Page 30 of 44
5.5. Exercise 4

Write a Java program that checks if a series of 10 numbers entered by the user in the
ascending order are consecutive (in this case, print congrats message) or not (in this
case, print the number of conflicts).

Example 1:
Number 1 = 10
Number 2 = 12
Conflict: 10 & 12 are not consecutive.
Number 3 = 14
Conflict: 12 & 14 are not consecutive.
Numb 4 = 1
er 5
Numb 5 = 1
er 6
Numb 6 = 1
er 7
Numb 7 = 1
er 8
Numb 8 = 1
er 9
Numb 9 = 2
er 0
Number 10 = 30
Conflict: 20 & 30 are not consecutive.
Unfortunately, you have 3 conflicts.

Example 2:
Numb 1 = 1
er
Numb 2 = 2
er
Numb 3 = 3
er
Numb 4 = 4
er
Numb 5 = 5
er
Numb 6 = 6
er
Numb 7 = 7
er
Numb 8 = 8
er
Numb 9 = 9
er
Number 10 = 10
Congrats. All numbers are consecutive.
Page 31 of 44
5.6. Exercise 5 (Homework)

Write a java program that simulates an electronic survey by reading answers (yes or
no) from different users.

The program asks users to enter their answers individually, where the answers should
be either 0 (yes), 1 (no), or -1 (to exit) only; if the user enters another value, the
system should display an error message. The program should count the frequency of
each answer and, at the end, it prints the statistics (total answers (excluding erroneous
answers), number and percentage of users answered yes and the same for users
answered no)

Example:

First user answer: 1


Next user answer: 0
Next user answer: 0
Next user answer: 2
You did not enter a valid
answer! Next user answer: 1
Next user answer: 0
Next user answer: 0
Next user answer: 1
Next user answer: 0
Next user answer: 0
Next user answer: -1

Questionnaire stats:
- Total answers: 9
- Yes answers: 6 (66.67%)
- No answers: 3 (33.33%)

Page 32 of 44
Lab 6 – Methods (Part 1)

6.1. Lab Goals


 Write and use methods
 Use Java API classes and their methods such as class Math
 Solve problems using nested repetition statement

6.2. Exercise 1
Write a Java method distance() that calculates the distance between two points
with the coordinates (x1, y1) and (x2, y2).

The distance between two points (x1, y1) and (x2, y2) is given by the following

formula: distance = √(x2-x1)2 + (y2-y1)2


Test your function using a main function and enter different values each time.

6.3. Exercise 2
𝑛!
Consider the following formula: 𝑃(𝑛, 𝑟) = .
(𝑛−𝑟)!

Write a Java program that computes the value of P(n,r), where n is given by the user
and r varying from 1 to n/2. (Hint: use nested loops).

The following are running examples:

Example 1:
n= 7
P(7,1) = 7
P(7,2) = 42
P(7,3) = 210

Example 2:
n = 10

Page 33 of 44
P(10, = 10
1)
P(10, = 90
2)
P(10, = 720
3)
P(10, = 504
4) 0
P(10, = 302
5) 40

6.4. Exercise 3
𝑛!
Consider the same formula as the previous exercise: 𝑃(𝑛, 𝑟) = .
(𝑛−𝑟)!

Write a Java method factorial() to compute the factorial value (n!) of a given number
received as parameter.

Then, write a main() method that computes and displays the value of P(n,r) (by
calling the factorial method), where n is given by the user and r varying from 1 to n/2.

6.5. Exercise 4 (Homework)


Write Java method to print each of the following patterns using nested loops. The size
of the shape is asked from the user using the main method then it is passed as
parameter to the relevant method.

# # # # # # # ## ## # #
# # # #
#
# # # # # # # # ## # ##
# # # #
#
# # # # # # # # ## # ###
# # # #
# # # # # # # ## # ####
# # # #
# # ## # # # # # # #####
# # #
# # ### # # # # # ######
# #
# # ### # # # # ######
# # #
# # ### # # # # ######
# # #
(a) ( (c) (d)
b
)

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


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

#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # ###### #
(e) (f) (g) (h) (i)

Hints:
 On the main diagonal, row = col.
 On the opposite diagonal, row + col = size + 1.

Page 34 of 44
Lab 7 – Methods (Part 1)

7.1. Lab Goals


 Write and use methods
 Use Java API classes and their methods such as SecureRandom
 Demonstrate method overloading concept
 Write and use recursive methods

7.2. Exercise 1
Write a Java method that generates and returns a random number between 2 values
received as parameters. You must consider 2 cases when there are or not difference
between values (please refer to slide 43 from 04 Methods). The function should check
if the difference is strictly positive otherwise replace it with the value 1.

Test your method using main as follows (bold values are input by the user):

Lowest value: 60
Highest value: 100
Diff. between values: 5
Number of random numbers: 50

60 90 70 65 70 60 75 100 100 85
8 9 6 9 7 6 8 7 9 9
0 0 0 5 5 5 0 0 0 0
8 6 9 6 8 9 7 8 6 7
5 5 5 0 5 5 5 5 0 0
9 8 6 6 9 9 8 6 9 7
0 0 5 5 0 0 0 0 5 5
6 9 7 7 9 6 6 6 8 6
0 0 0 0 0 0 5 0 5 0
Page 35 of 44
7.3. Exercise 2
Define 5 overloaded methods named compute() by considering the following main
method:
public static void main(String[] args)
{
int a = 5, b = 9, c = -2;

boolean t = true, f = false;

// sum of 2 integers
System.out.printf("compute(%d,%d): %d\n", a, b, compute(a, b));

// sum of 3 integers
System.out.printf("compute(%d,%d,%d): %d\n", a, b, c, compute(a, b, c));

// logic "or" between 2 booleans System.out.printf("compute(%b,


%b): %b\n", t, f, compute(t, f));

// logic "or" between 3 booleans


System.out.printf("compute(%b,%b,%b): %b\n", t, f, f, compute(t, f, f));

// if the integer is positive returns the boolean as it is,


// otherwise returns its negation System.out.printf("compute(%d,
%b): %b\n", a, f, compute(a, f)); System.out.printf("compute(%d,
%b): %b\n", -a, f, compute(-a, f));

// if the boolean is true returns the integer as it is,


// otherwise returns its negative value
System.out.printf("compute(%b,%d): %d\n", t, b, compute(t, b));
System.out.printf("compute(%b,%d): %d\n", f, b, compute(f, b));
}

7.4. Exercise 3
Two functions are said to be mutually recursive if the first calls the second, and in
turn the second calls the first.

Write two mutually recursive Java methods that compute members of the Hofstadter
Female and Male sequences defined as:

Page 36 of 44
Write the following code fragment inside the main method to test F and M methods:
int i;
for (i = 0; i < 20; i++)
System.out.printf("%2d ", F(i));

System.out.println();
for (i = 0; i < 20; i++)
System.out.printf("%2d ", M(i));

System.out.println();

7.5. Exercise 4
Write a Java program that generates a password randomly. The program asks the user
to enter the length of the password and generates randomly an alphanumeric password
with the specified length.
You have to define and call a method generatePassword() which takes an
integer parameter (n) and prints a random password (character by character using
SecureRandom class) of length n following this pattern:

 Generate 2 random letters, then


 Generate 1 random digit

Hints: Numerical representations of:

 Letters: start from ‘a’=97 to ‘z’=122


 Digits: start from ‘0’=48 to ‘9’=57

Run 1
Password length = 5
Password = et7ar

Run 2
Password length = 9
Password = fh6hv7cz2

Page 37 of 44
Lab 8 – Arrays (Part 1)

8.1. Lab Goals


 Declaring and Creating arrays
 Passing arrays to methods

8.2. Exercise 1
Write and test a Java method maximum() that returns the maximum of an array of n
integers.

8.3. Exercise 2
Write and test a Java method occurrences() that computes and displays the number
of occurrences of number p in an array of n integers.

8.4. Exercise 3
Write and test a Java method that performs a circular right shift on an array of n integers.

8.5. Exercise 4
First, write a Java method remove that takes 2 parameters: 1) a non-empty integer
array with distinct values and an existing integer value to be removed from the array.
The method removes the value from its position in the array by pushing to the left all
the elements from after this position to the end of the array. The method remove
returns the position of the removed element and replaces the last element with 0 after
moving the elements.
Suppose that the user will enter distinct values of the array’s elements and an existing
value to be removed from the array. Suppose also that the user will never ask to
remove the last element.
Second, write two java methods readArray(int[]a) and printArray(int[]a) that
reads/writes the elements of an array passed in parameter from/to the standard
input/output.

Page 38 of 44
Finally, use the following main method to test your different methods:

public class RemoveElement {


private static Scanner input = new Scanner(System.in);

public static void main(String[] args)


{
int[] array = new int[10];
System.out.print("Enter 10 elements: ");
readArray(array);

System.out.print("Element to remove: ");


int number = input.nextInt();

int rei = remove(array, number);


System.out.println("Removed element index: " +
rei);

System.out.print("Array after remove: ");


printArray(array);
}
}

Run:
Enter 10 elements: 4 5 3 7 6 8 2 1 9 10
Element to remove: 3

Removed element index: 2


Array after remove: 4 5 7 6 8 2 1 9 10 0

Page 39 of 44
Lab 9 – Arrays (Part 2)

9.1. Lab Goals


 Solve problems using arrays and multidimensional Arrays
 Define methods using variable-length argument lists
 Using command-line arguments

9.2. Exercise 1
Write a Java method that takes the elements of a 2-dimensional array a (n * m), then it
gives back the sum of the lines (separately) in an array b (n) and the product of the
columns (separately) in an array c (m).

Test your method by writing a complete program.

9.3. Exercise 2
Write a Java application that calculates the sum of a series of integers that are passed
to method sum() using a variable-length argument list. Test your method with several
calls, each of which with different number of arguments.

9.4. Exercise 3
Write a Java application that receives the name and the year of birth of a person using
command-line arguments, then calculate the age of the person and print a greeting
message with the age.

Running example:

$java ComputeAge Omar 1420

Hello Omar, your age is 19.

Page 40 of 44
Lab 10 – Strings

10.1. Lab Goals


 Manipulate characters based on their numeric representation
 Process strings using class String methods

10.2. Exercise 1
Write a Java application which prompts the user for a String, counts the number of
vowels (a, e, i, o, u, A, E, I, O, U) and digits (0-9) contained in the string, and prints
the counts and the percentages (with 2 decimal digits). An example of execution is as
follow:
Enter a String: testing12345
Number of vowels: 2 (16.67%)
Number of digits: 5 (41.67%)

You have to define and test the method void checkVowelsDigits(String str):
that counts and displays number and the percentage of vowels and digits.

Hints:

 To check if a char c is a digit, you can use boolean expression (c >= '0' && c
<= '9'); or use built-in boolean function Character.isDigit(c).
 You could use in.next().toLowerCase() to convert the input String to
lowercase reduce the number of cases.
 To print a % using printf(), you need to use %%. This is because % has a
special meaning in printf(), e.g., %d and

Page 41 of 44
10.3. Exercise 2
Write a Java method named getSiteName() that receives a String representing a URL
and returns the name of the site extracted from the URL. Test your function using
main method as follows:
Enter site URL: http://www.google.com
Site name is: Google

Hint: You may use String methods such as indexOf(), lastIndexOf(), substring(),
and toUpperCase(), instead of using a loop.

Page 42 of 44
Lab 11 – Files

11.1. Lab Goals


 Create a sequential-access text file
 Read data from a sequential-access text file
 Update sequential-access file

11.2. Exercise 1
Consider the file named file.txt which contains personal information (id, name,
salary):

A1 An 3000
23 na
A2 Al 4000
34 ex
A9 Ja 5000
86 me

Write a java application that allows the user to enter an ID of a person and additional
salary, then it will update the file.
The program output will look like:
Enter ID: A123
Enter additional salary: 2000

The content of the file will be (after running the program):

A1 An 5000
23 na
A2 Al 4000
34 ex
A9 Ja 5000
86 me
Page 43 of 44
11.3. Exercise 2
Consider the file named results.txt which contains students’ information (id,
name, marks):

100 Fahd 93
101 Omar 50
102 Anas 58

Complete the following program that reads a file (where the file name is provided to
the main method as parameter) that contains the students’ information, adds 2 to the
total marks (without updating the file), and prints student information and whether is
passed or not.

public class ProcessGrades {


public static void main(String[] args) throws Exception {
String fileName = args[0];
Scanner s = new Scanner(Paths.get(fileName));
while(s.hasNext()) {
// add you code here
}
}
}

You must pass the name of the file as option while running the file. So you can
run your program using a command line similar to: java ProcessGrades
results.txt

It is supposed to have the following output (after running the program):

100 Fahd 95.00 Passed


101 Omar 52.00 Failed
102 Anas 60.00 Passed

Page 44 of 44

Das könnte Ihnen auch gefallen