Download Lab 09: Methods

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Kingdom of Saudi Arabia
Ministry of Higher Education
University of Hail
College of Computer Science and Engineering
Department of Computer Science and Software Engineering
ICS102: fundamentals of Computer Programming (201402)
preparedd By: Ebtisam Hamed
Lab 01: Getting
Started with Java
Objectives:
Appreciate the importance of:
 Comments,
 Indentation,
 Good Naming Style, and
 Recognizing Syntax Errors.
2. Comments
Comments are English sentences inserted in a program to explain its purpose.
We use comments to explain the purpose of a class, a method or a variable.
There are two types of comments:
1) Block comment
/* … */
o Comments are ignored by the compiler.
o Any message enclosed inside /* … */ is treated as a comment.
o This type of comment can span more than one line.
2) Line comment
// …
o Any message following double forward slash, //, up to the end of the line is
also considered a comment.
o Notice that this type of comment cannot span more than one line.
o It is often used to comment variables.
You are expected to:
o Write brief information about yourself at the beginning of each program,
o Write comments explaining each program you write in this course, and
o Comment every variable whose purpose is not obvious from its name.
3. Indentation
Indentation involves using tabs, spaces, and blank lines to visually group related
statements together.
You shall:

Push the statements inside a class, method, or structural statements such as
if, while,… etc. by at least three or four spaces or a tab character;

Separate between variable declarations and method declarations by a blank
line; and

Separate adjacent methods by a blank line.
4. Naming Style
In programs, variable names should clearly suggest their meanings. This is called the
naming style.
Good naming style makes your program easier to read and easier to correct errors.
For example, the A coefficient of an equation should be called: aCoefficient,
coefficient_A, or similar; but never a, b, x, or z.
The use of abbreviations is also discouraged.
5. Recognizing Syntax Errors
When you make syntax errors in your program the compiler gives error messages and
does not create the bytecode file. It saves time and frustration to learn what some of these
messages are and what they mean. Unfortunately, at this stage in the game many of the
messages will not be meaningful except to let you know where the first error occurred.
Your only choice is to carefully study your program to find the error.
Correcting Syntax Errors
Some things to remember:
 Java is case sensitive, so, for example, the identifiers public, Public, and
PUBLIC are all considered different.
 When the compiler lists lots of errors, fix the first one (or few) and then
recompile.
 Close opened brackets, braces, and quotes.
 It is always important to remember to end every statement in Java with a
semicolon ‘;’.
Exercises
Exercise 1:
(Hello.java)
Write the following Java program.
/*
* By: .
* ID:
* UOH, CCSE, ICS Dept.
*/
/*
* Print a message to the screen
*/
public class Hello {
public static void main(String[] args) {
System.out.println("Hello World”);
}
}
Exercise 2:
(Printing.java)
What do the following statements print? Don't guess; write programs to find out.
a. System.out.println(“3 + 4”);
b. System.out.println(3 + 4);
c. System.out.println(3 + “4”);
Exercise 3:
OutPut:
3 + 4
7
34
(NamePrinter.java)
Write a program NamePrinter that displays your name inside a box on the console screen,
like this:
Do your best to approximate lines with characters, such as |, -, and +.
class NamePrinter {
public static void main(String[] args) {
System.out.println("+------+");
System.out.println("| Dave |");
System.out.println("+------+");
}
}
Exercise 4:
(FacePrinter.java)
Write a program FacePrinter that prints a face, using text characters, hopefully better
looking than this one:
Use comments to indicate the statements that print the hair, ears, mouth, and so on.
/*
* ///////
* (|00|)
* | ^ |
* | [_] |
* ----**/
class NamePrinter {
public static void main(String[] args) {
System.out.println(" ///////");
System.out.println("( | 0 0 | )");
System.out.println(" | ^ |");
System.out.println(" | [_] |");
System.out.println(" -----");
}
}
Kingdom of Saudi Arabia
Ministry of Higher Education
University of Hail
College of Computer Science and Engineering
Department of Computer Science and Software Engineering
ICS102: fundamentals of Computer Programming (201402)
preparedd By: Ebtisam Hamed
Lab 02: Detecting Syntax and Logic Errors
Objectives:




Detecting syntax Errors,
Detecting Logical Errors.
To learn how Java handles math operations on integers and decimals
Writing simple programs to calculate Arithmetic expressions
1. Syntax Errors (compile time errors)








class name does not match file name
(usually this is due to uppercase vs. lower case mistake or simple typo)
misspelled variable name
(use of variable name does not match name in its declaration)
missing semicolon after assignment or method call statement
missing semicolon after variable definition
missing semicolon after import statement
giving semicolon after method signature
redefining the type of a variable (defining a variable which is already defined)
confusing one character string "x" with character 'x'
Later ( not taken yet)





missing parenthesis "(" and ")" around condition in if or while statement
missing parentheses "(" and ")" in method call without arguments
missing the variable type for an argument in the parameter list of method
declaration
supplying the variable type for an argument in the parameter list of method call
missing return statement at end of some unreachable path in code declaring
method as static when it mentions instance variables
2. How Java handles math operations on integers and decimals
1. When integers interact with integers, the result is always integer.
2. When decimals interact with decimals, the result is always decimal.
3. When integers and decimals interact, the result will always be in decimal form.
Exercises
Exercise 1:
1. Down load the file cube.java
2. Debug the file and correct syntax errors found in file.
3.
Compile and run the program.
\\ program to calculate volume and surface area of cube
public class cube
{
public static void main( )
{
int height=3.0
int dummy;
double cubeVolume = height * height * Height;
double surfaceArea = 8 * height;
System.out.print("Volume = );
System.out.println(cubeVolume ;
System.out.print("Surface area =" );
System.out.println(surfaceArea);
System.out.println(dummy);
}
// program to calculate volume and surface area of cube
public class cube
{
public static void main( )
{
double height=3.0 ;
int dummy=0;
double cubeVolume = height * height * height;
double surfaceArea = 8 * height;
System.out.print("Volume = ");
System.out.println(cubeVolume) ;
System.out.print("Surface area =" );
System.out.println(surfaceArea);
System.out.println(dummy);
} }
Exercise 2:
1. Down load the file Average.java
2. Debug the file and correct logical found in file.
3.
Compile and run the program.
public class Average {
public static void main(String[]
args) {
//this program will
calculate the average of 4 and 10
int x =4 , y= 10 ;
public class Average {
public static void main(String[]
args) {
//this program will
calculate the average of 4 and 10
int x =4 , y= 10 ;
System.out.println((4+10)/2);
}
System.out.println(4+10/2);
}
}
}
Exercise 3:
Categorize each of the following situations as a
compile-time error
run-time error
logical error
a. multiplying two numbers when you meant to add them
logical error.
b. dividing by zero
run-time error.
c. Forgetting a semicolon at the end of a programming statement
compile-time error.
d. Producing inaccurate results
logical error.
e. typing a { when you should have typed a (
compile-time error.
Exercise 4:
write a java program following the instructions :
public class Lab02 {
public static void main(String args[]) {
//1. declare m1 m2 m3 to be integers
//2. assign 6 , 18 , 10 to m1, m2 , m3 respectively
//3. print the result of the following operations
//4. print the result of the following operations
m 1%m 2, m 3%m 1
m1
m2
// 5. print the output of the following operation 6/18.0
// why result in part 4 and 5 different
}
}
class Lab02 {
public static void main(String args[]) {
int m1, m2, m3;
m1=6;
m2=18;
m3=10;
System.out.println(m1%m2);
System.out.println(m3%m1);
System.out.println(m1/m2);
System.out.println(6/18.0);
}
}
OutPut:
6
4
0
0.3333333333333333
Kingdom of Saudi Arabia
Ministry of Higher Education
University of Hail
College of Computer Science and Engineering
Department of Computer Science and Software Engineering
ICS102: fundamentals of Computer Programming (201402)
preparedd By: Ebtisam Hamed
Lab 03: Java Expressions
Objectives
Practicing:
 Declaring and initializing variables and constants.
 Using normal and shorthand assignment statements.
 Using arithmetic operators (+, -, *, /, %) in expressions.
 Using parentheses to enforce our precedence rules.
Exercises
Exercise 1:
Let (int x = 9, double y = 2.3, and double z = 5.2).
Complete the following table (without Pc)
Arithmetic Expression
x+y*z
x/y*z
x/2+y/2
x/2
x%2
x%5*3+1
(y + 3) * 2
z / (1 + 1)
Result
Interpretation
Exercise 2: (AverageGPA.java)
Write a program that defines and initializes the GPAs of three students {student1,
student2, student3), then computes and prints the average GPA.
class AverageGPA {
public static void main(String args[]) {
double student1, student2, student3;
student1=3.25;
student2=2.50;
student3=4.00;
System.out.println((student1+student2+student3)/3);
}
}
Exercise 3: (Division.java)
Design then implement a Java program that defines and initializes two integers a = 18
and b = 4 then computes and displays the followings:
- the quotient of dividing a by b,
- the remainder of dividing a by b.
class Division {
public static void main(String args[]) {
int a = 18 ;
int b = 4 ;
System.out.println(a/b);
System.out.println(a%b);
}
}
Kingdom of Saudi Arabia
Ministry of Higher Education
University of Hail
College of Computer Science and Engineering
Department of Computer Science and Software Engineering
ICS102: fundamentals of Computer Programming (201402)
preparedd By: Ebtisam Hamed
Lab 04: Strings
Objectives
Designing and implementing Java programs that deal with:






String Class Objects.
String Concatenation (+).
String Class Methods (length, equals, toLowerCase,
toUpperCase, trim, charAt, substring, indexOf).
String Indices
Escape Sequences (\”, \’, \\, \n, \r, \t).
The Imputable Characteristic of the String Object.
Example
The following example generates a password for a student using his initials and age.
(Note: do not use this for your actual passwords).
/*
* generates a password for a student using his initials and age
*/
public class PasswordMaker {
public static void main(String[] args) {
String firstName = "Amr";
String middleName = "Ahmed";
String lastName = "Al-Ghamdi";
int age = 20;
// extract initials
String initials = firstName.substring(0,1) +
middleName.substring(0,1) +
lastName.substring(0,1);
// append age after changing the initials to lower case
String password = initials.toLowerCase() + age;
System.out.println("Your Password = " + password);
}
}
Exercises
Exercise 1: ((REVISION))
Design and implement a program that computes and displays number of
thousands, hundreds, tens, and ones in n. ((hint: use integer division))
For example, if n is 543, the output should be:
No
No
No
No
of Thousands:
of Hundreds:
of Tens:
of Ones:
0
5
4
3
Solution:
class Lab4 {
public static void main(String args[]) {
int n = 543;
System.out.println("No of Thousands: " + 543/1000);
System.out.println("No of Hundredss: " + 543/100);
System.out.println("No of Tens: " + (543%100)/10);
System.out.println("No of Ones: " + 543%10);
}
}
Exercise 2:
Write the results of each expression.
String str1 = "Frodo Baggins";
String str2 = "Gandalf the GRAY";
str1.length()
13
str1.indexOf("o")
2
str2.toUpperCase()
GANDALF THE GRAY
str1.substring(6,8)
Ba
str2.substring(3, 7)
dalf
Exercise 3:
(StringWelcome.java)
Design and implement a Java program that will do the following operations to this string
“Welcome! This is “ICS102” Course”:
 Convert all alphabets to capital letters and print out the result;
 Convert all alphabets to lower-case letters and print out the result; and
 Print out the length of the string.
 Print out the index of the word Course.
class StringWelcome {
public static void main(String args[]) {
String str1 = "Welcome! This is “ICS102” Course";
System.out.println(str1.toLowerCase());
System.out.println(str1.toUpperCase());
System.out.println(str1.length());
System.out.println(str1.indexOf("Course"));
}
}
Exercise 4:
OutPut:
welcome! this is “ics102” course
WELCOME! THIS IS “ICS102”
COURSE
32
26
(PasswordMaker2.java)
Modify the example shown above in such a way that instead of taking the name initials, it
takes the middle letter from the first, middle and last name.
class PasswordMaker {
public static void main(String[] args) {
String firstName = "Amr";
String middleName = "Ahmed";
String lastName = "Al-Ghamdi";
}
System.out.println("Your Password = " + firstName.substring(1,2) +
middleName.substring(2,3) +
lastName.substring(4,5));
}
OutPut:
Your Password = mmh
Exercise 5:
(CourseSpliter.java)
Normally a UOH course is described as follow: ABC 123 : Course Description. Design
then implement a Java program that will split then print the 3 components of the
following course description: ICS 102 : Introduction to Computing I as shown below:
(hint: use substring method)
Course Name: ICS
Course Number: 102
Course Description: Introduction to Computing
I
class CourseSpliter {
public static void main(String args[]) {
String str1 = "ICS 102 : Introduction to Computing I ";
System.out.println(str1.substring(0, 3));
System.out.println(str1.substring(4, 7));
System.out.println(str1.substring(10, 37));
}
}
Kingdom of Saudi Arabia
Ministry of Higher Education
University of Hail
College of Computer Science and Engineering
Department of Computer Science and Software Engineering
ICS102: fundamentals of Computer Programming (201402)
preparedd By: Ebtisam Hamed
Lab 05: Console Input
Objectives
Designing and implementing Java programs that deal with:
 Console output using System.out object.
 println and print methods.
 Importing packages and classes using import statement.
 Console input using Scanner class:
1. Scanner class constructors.
2. Scanner class methods:
1.
2.
3.
4.
int nextInt()
double nextDouble()
String next()
String nextLine()
Exercise 1:
Write statements to prompt for and read the user’s age using a Scanner variable named in.
import java.util.Scanner;
class Lab5 {
public static void main(String args[]) {
Scanner in= new Scanner(System.in);
System.out.print("Please enter your age ");
int age = in.nextInt();
}
}
Exercise 2:
What is wrong with the following statement sequence?
System.out.print("Please enter the unit price: ");
double unitPrice = in.nextDouble();
int quantity = in.nextInt();
You must wite an object from class Scanner:
Scanner in= new Scanner(System.in);
Exercise 3:
Write a program that reads a number and displays the square, cube
import java.util.Scanner;
class Lab5 {
public static void main(String args[]) {
Scanner in= new Scanner(System.in);
System.out.print("Please enter a number ");
int a = in.nextInt();
System.out.println(a*a);
System.out.println(a*a*a);
}
}
Exercise 4:
Write a program that prompts the user for a radius and then prints
• The area and circumference of a circle with that radius
• The volume and surface area of a sphere with that radius
volume = (4/3) r3
surface = 4 r2
import java.util.Scanner;
class Lab5 {
public static void main(String args[]) {
Scanner in= new Scanner(System.in);
System.out.print("Please enter a radius");
double a = in.nextDouble();
double area= Math.PI*a*a;
double circumference = 2*Math.PI*a;
System.out.println("area"+area);
System.out.println("circumference"+circumference);
double volume =(4/3)*Math.PI*a*a*a;
double surface =4*Math.PI*a*a;
System.out.println("volume"+volume);
System.out.println("surface"+surface);
}
}
Exercise 5:
Write a program that asks the user for the lengths of the sides of a rectangle. Then
print the area and perimeter of the rectangle
Rectangle Area = Length * Width
Rectangle Perimeter = 2(Length+ Width)
import java.util.Scanner;
class Lab5 {
public static void main(String args[]) {
Scanner in= new Scanner(System.in);
System.out.print("Please enter Length");
double L = in.nextDouble();
System.out.print("Please enter Width");
double W = in.nextDouble();
double area= L*W;
System.out.println("area"+area);
double perimeter = 2*(L+W);
System.out.println("perimeter "+perimeter );
}
}
Exercise 6:
Write an application that asks the user to enter two integers, obtains them from the
user and prints their sum, product, difference and division.
Hint : think about variables you need to define , packages you need to import
Sample Output:
import java.util.Scanner;
class Lab5 {
public static void main(String args[]) {
Scanner in= new Scanner(System.in);
System.out.print("Please enter number: ");
double a1 = in.nextDouble();
System.out.print("Please enter number: ");
double a2 = in.nextDouble();
double sum= a1+a2;
System.out.println("Sum is "+sum);
double product = a1*a2;
System.out.println("Product is "+product );
double difference= a1-a2;
System.out.println("Difference is "+difference );
double division = a1/a2;
System.out.println("Division is "+division );
}
}
Kingdom of Saudi Arabia
Ministry of Higher Education
University of Hail
College of Computer Science and Engineering
Department of Computer Science and Software Engineering
ICS102: fundamentals of Computer Programming (201402)
preparedd By: Ebtisam Hamed
Lab 06: Branching Mechanism
Objectives
Designing and implementing Java programs that deal with:
 if-else statements.
 Multiway if-else statements.
 switch statements.
Reminder
1. Scanner class constructors.
2. Scanner class methods:
1.
2.
3.
4.
int nextInt()
double nextDouble()
String next()
String nextLine()
Exercises
Exercise 1:
(even.java)
Write a program that reads an integer x and checks ether it is divisible by 2 , 3 and 5.
Print appropriate messages.
import java.util.Scanner;
class a {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter a number:");
int x = in.nextInt();
if (x%2==0 && x%3==0 && x%5==0)
System.out.println("divisible by 2,3 and 5");
else
System.out.println("invalid");
Exercise 2:
}}
(HonorCalculator.java)
Design and implement a Java program that takes a student GPA as an input and then
prints a message dialoge with the equavilant distinction (First, second or third distinction)
as follows:
GPA >= 3.75
: First distinction
3.5 <= GPA < 3.75 : Second distinction
3.0 <= GPA < 3.5 : Third distinction
GPA < 3.0
: There is no distinction awarded
Hint: to read double value using Scanner object
import java.util.Scanner;
class a {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter your GPA:");
double x = in.nextDouble();
if (x>=3.75)
System.out.println("First Distinction");
else
if (x<3.75 && x>=3.5)
System.out.println("second Distinction");
else
if (x<3.5 && x>=3)
System.out.println("Third Distinction");
else
System.out.println("There is no distinction awarded"); }}
Exercise 3:
(Traffic.java)
Design and implement a Java program that get a traffic violation number and output the
traffic violation title and price based on the following table: Hint (use Switch)
Number
1
2
3
4
5
6
else
Title
Not stopping at (STOP) signs
Usage of improper light
Sudden start-up (heeling)
Violating speed limit
Leaving the car unattended on public streets
Destroying the Denver boot
undefined
Price
SR 100
SR 200
SR 200
SR 100
SR 200 + Towing cost
SR 2500 + Dismiss
undefined
import java.util.Scanner;
public class a{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a traffic violation number");
int trafficVoilationNumber = keyboard.nextInt();
switch(trafficVoilationNumber){
case 1:
System.out.println("Title: Not stopping at (STOP) signs");
System.out.println("Price: SR 100");
break;
case 2:
System.out.println("Title: Usage of improper light");
System.out.println("Price: SR 200");
break;
case 3:
System.out.println("Title: Sudden start-up (heeling)");
System.out.println("Price: SR 200");
break;
case 4:
System.out.println("Title: Violating speed limit");
System.out.println("Price: SR 100");
break;
case 5:
System.out.println("Title: Leaving the car unattended on public streets");
System.out.println("Price: SR 200 + Towing cost");
break;
case 6:
System.out.println("Title: Destroying the Denver boot");
System.out.println("Price: SR 2500 + Dismiss");
break;
default :
System.out.println("Title: undefined");
System.out.println("Price: undefined");
break;
}}}
Exercise 4:
(Menu.java)
Design and implement a Java program that prompts the user to enter 2 numbers of type
int then displays a menu on the screen as shown below:
a. Print
b. Print
c. Print
- Choose
sum
sum and average
sum, average, and max
an option [a, b, c]: _
The program reads the user’s option as a integer using Scanner object and then display
the result.
import java.util.Scanner;
public class Menu{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the first number (Integer)");
int number1 = keyboard.nextInt();
System.out.println("Enter the second number (Integer)");
int number2 = keyboard.nextInt();
System.out.println("a. Print sum ");
System.out.println("b. Print sum and average");
System.out.println("c. Print sum, average, and max");
System.out.println(" - Choose an option [a, b, c]:");
char choice = keyboard.next().charAt(0);
switch(choice){
case 'a':
System.out.println("Sum is : "+(number1+number2));
break;
case 'b':
System.out.println("Sum is : "+(number1+number2));
System.out.println("Average is :"+ ((number1+number2)/2));
break;
case 'c':
System.out.println("Sum is : "+(number1+number2));
System.out.println("Average is :"+ ((number1+number2)/2));
if(number1 >= number2)
System.out.println("max is :"+number1);
else
System.out.println("max is :"+number2);
break;
break;
default :
System.out.println("Sorry , invalid input");
break;
}}}
Kingdom of Saudi Arabia
Ministry of Higher Education
University of Hail
College of Computer Science and Engineering
Department of Computer Science and Software Engineering
ICS102: fundamentals of Computer Programming (201402)
preparedd By: Ebtisam Hamed
Lab 07: Looping
Objectives
Designing and implementing Java programs that deal with:
 while loop statement.
 do-while loop statement.
 for loop statement.
 Issues related to loops:
1.
2.
3.
4.
nested loops
break statement
continue statement
common kinds of loop errors.
Syntax Reference
The following are syntaxes for the three types of loops of Java along with some
examples.
do-while Loop Statement Syntax
int start = 0;
do
{
do
{
Statement_Block
} while (Boolean_Expression);
System.out.println(start)
;
start++;
} while (start <= 3);
while Loop Statement Syntax
int start = 0;
while (Boolean_Expression)
{
Statement_Block
}
while (start <= 3)
{
System.out.println(start);
start++;
}
for(int start = 0; start <= 3;
start++)
{
System.out.println(start);
}
for Loop Statement Syntax
for(initializing; Boolean_Expression; Update)
{
Statement_Block
}
0
1
2
3
Exercises
Exercise 1:
(UOH.java)
Design and implement a program that will print
(A) UOH IS THE BEST 10 times
(B) HAIL 5 times
NOTE 01: Use only 1 loop.
NOTE 02: Your output may be in any order but it is preferable to do as:
UOH IS
UOH IS
HAIL
UOH IS
UOH IS
HAIL
UOH IS
UOH IS
HAIL
...
THE BEST
THE BEST
THE BEST
THE BEST
THE BEST
THE BEST
class Lab7 {
public static void main(String[] args) {
for(int i=0;i<=4;i++){
System.out.println ("UOH IS THE BEST");
System.out.println ("UOH IS THE BEST");
System.out.println ("HAIL");
}
}
}
Exercise 2:
(Series.java)
Design and implement a program that will find the result of the following:
i 150
 (2i  5)
i  53
class Lab7 {
public static void main(String[] args) {
int d=0;
for(int i=53;i<=150;i++){
int sum=0;
sum=2*i+5;
d=sum+i;
}System.out.println (d);
}}
Exercise 3:
(Dividors.java)
Write a program that reads an alphabetic character and a number of repeat then
prints a triangle of alphabet. Example:
Enter an alphabetic character: t
Enter number of repeating: 5
The output is:
t
t t
t t t
t t t t
t t t t t
import java.util.Scanner;
class Lab {
public static void main(String[] args) {
System.out.println("Enter Char");
Scanner in=new Scanner(System.in);
String a=in.next();
System.out.println ("Enter number");
int n=in.nextInt();
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
System.out.print (a);
}
System.out.println();
} }
}
Exercise 4:
(Swap.java)
Design and implement a program that will enclose exercises 1, 2 and 3 inside a do-while
loop, to make a user choose among the three which ones he wants to execute. The
program should show the following menu:
1. Exercise 01 - Print
2. Exercise 02 - Summation
3. Exercise 03 – Division
4. Exit
Enter your choice [1, 2, 3, or 4]:
import java.util.Scanner;
public class Lab7 {
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
int x= in.nextInt();
do{
switch(x){
case 1:
for(int i=0;i<=4;i++){
System.out.println ("UOH IS THE BEST");
System.out.println ("UOH IS THE BEST");
System.out.println ("HAIL");
}
break;
case 2:
int total=0;
for(int i=53;i<=150;i++){
int sum=0;
sum=2*i+5;
total=sum+total;
} System.out.println (total);
break;
case 3:
Scanner n3=new Scanner(System.in);
int d=n3.nextInt();
System.out.println("Please enter a number:");
System.out.println("Numbers dividing"+ d +"are");
for(int i=1;i<d;i++){
if(d%i ==0){
System.out.println (i);}}
break;
default:
in.close();
break;
}x++;
}while(x<=4);
}
}
Kingdom of Saudi Arabia
Ministry of Higher Education
University of Hail
College of Computer Science and Engineering
Department of Computer Science and Software Engineering
ICS102: fundamentals of Computer Programming (201402)
preparedd By: Ebtisam Hamed
Lab 08: Arrays
Objectives
Designing and implementing Java programs that deal with:

Arrays
1. Declaring Arrays’ Objects.
2. length variable.
Notes
EXAMPLES: for declearing an array
char[] line = new char[80];
String[] word = new String[SIZE];
Book[] book = new Book[3 * 25];

An array is an object.

An array has ONLY 1 instant variable, which is named length.
int[] grade = new int[13];
then grade.length has a value
of 13.
Exercises
Exercise #01:
(ArrayReversing.java)
Design and implement a java code that should reverse the sequence of elements in an
array, for example with an array containing
1 4 9 16 3 7
then the new array will be printed as:
7 3 16 9 4 1.
class Lab8ex1 {
public static void main(String[] args) {
int[] a= new int[6];
a[0]=1;
a[1]=4;
a[2]=9;
a[3]=16;
a[4]=3;
a[5]=7;
for(int i=0; i<a.length ; i++){
System.out.print(a[i]);
}
System.out.println();
for(int i=a.length-1; i >= 0; i--){
System.out.print(a[i]);
}
}
}
Exercise #02:
(ComaringArraysI.java)
Design and implement a java code that should check whether the two arrays a and b have
the same elements on some order, ignoring multiplicities.
For example, the two arrays
1 4 1
and
4 1
would be considered to have the same set.
class Lab8ex2 {
public static void main(String[]args) {
int[] array1 = {1, 4, 1};
int [] array2= {4,1};
int cnt=0;
for(int i=0;i<array1.length;i++){
for(int j=0; j<array2.length;j++){
if(array1[i]==array2[j]){
cnt++;
}}
}
if (cnt==array1.length){
System.out.print("have same elements");
}
else
System.out.print("have not same elements");
}
}
Exercise #03:
(maxeven.java)
Write a program to read elements of array of 10 digits (integers) and find
the largest number , sum of even numbers (∑) and count of even
numbers.
import java.util.Scanner;
import java.util.Collections;
import java.util.Arrays;
class LLL {
public static void main(String[] args) {
int[] a = new int[10];
Scanner in = new Scanner(System.in);
for(int i = 0; i<a.length; i++) {
a[i] = in.nextInt();
}
//==================Max========================
int max = 0;
for ( int j = 0; j < a.length; j++) {
if ( a[j] > max) {
max = a[j];
}}
System.out.println("Max is:" +max);
\
//=================Sum of Even=========================
int sum=0;
for ( int j = 0; j < a.length; j++) {
if ( a[j] %2==0) {
sum=sum+a[j];
}}
System.out.println("Sum of even is:" +sum);
//=================Count of Even=========================
int count=0;
for ( int j = 0; j < a.length; j++) {
if ( a[j] %2==0) {
count++;
}}
System.out.println("Count of even is:" +count);
}
}
Kingdom of Saudi Arabia
Ministry of Higher Education
University of Hail
College of Computer Science and Engineering
Department of Computer Science and Software Engineering
ICS102: fundamentals of Computer Programming (201402)
preparedd By: Ebtisam Hamed
Lab 09: Methods
Objectives
Designing and implementing Java programs that deal with:

Methods
1. Declaring Methods.
2. Calling methods
3. Calling pre defined methods.
Notes
A method is a set of code which is referred to by name and can be called
(invoked) at any point in a program simply by utilizing the method's name.
Think of a method as a subprogram that acts on data and often returns a value.
Each method has its own name.
When that name is encountered in a program, the execution of the program
branches to the body of that method.
When the method is finished, execution returns to the area of the program code
from which it was called, and the program continues on to the next line of code.
Exercises
Example #01:
1. Define
(calculate.java)
two
methods, adder and welcome
2. note that adder returns an integer; welcome does not
value
Solution :
public static int adder(int x, int y) {
return x+y;
}
public static void welcome(String s) {
System.out.println(“WELCOME Mr. “ + S);
}
return
Execute the following code
public
class Calculate{
// write adder method here
// write welcome method here
public static void main(String[] args){
welcome(“Ahmad”);
welcome(“Mona”);
welcome(“Tahani”);
System.out.println( adder(8, 10));
System.out.println( adder(80, 20));
System.out.println( adder(12, 18));
}}
Exercise #02:
Write the a method that takes one integer as input and outputs “odd” if the
number is odd and “even” otherwise.
class lab8{
public static String EvenOrOdd(int n) {
if (n%2==0){
return "even";}
else return "odd";}
public static void main(String[] args){
System.out.println( EvenOrOdd(8));
System.out.println( EvenOrOdd(2));
System.out.println( EvenOrOdd(1));
}}
Exercise #03:
Write the a method that takes one integer as input and outputs “positive” if
the number is positive and “negative” otherwise.
class lab8{
public static String PositiveOrNegative(int n) {
if (n>=0){
return "positive";}
else return "negative";}
public static void main(String[] args){
System.out.println( PositiveOrNegative(-10));
System.out.println( PositiveOrNegative(2));
System.out.println( PositiveOrNegative(0));
}}
Exercise #04:
Write the a method that takes height and width of rectangle and returns the area
of the rectangle.
class lab8{
public static double Area(double h, double w) {
return h*w;}
public static void main(String[] args){
System.out.println( Area(2,5));
System.out.println( Area(1,6));
}}
Kingdom of Saudi Arabia
Ministry of Higher Education
University of Hail
College of Computer Science and Engineering
Department of Computer Science and Software Engineering
ICS102: fundamentals of Computer Programming (201402)
preparedd By: Ebtisam Hamed
Lab 01: Classes
Objectives
Designing and implementing Java programs that deal with:
 A class definition
 Object members:
1. Instant variables … characteristics … Math.PI
2. Methods … behaviors and operations … Math.max(10,3)


The new operator to create a new object … copy machine
Parts of method definition:
1. Header … name, input type, return type, who allowed to use
2. Body … job need to be done

The return statement:
1. In a void method … optional
2. In a method that returns value … must
Syntax Reference
The following are syntaxes for the three types of loops of Java along with some
examples.
User Defined Method Syntax
[modifiers] return_type method_name ([parameter_list])[throws_clause]
{
[statement_list]
}
int average(int a, int b)
{
return (a + b) / 2;
}
public String readLine()
{
Scanner keyboard = new Scanner(System.in);
System.out.print(“Enter a Sentence: ”);
return keyboard.nextLine();
}
void output(String msg)
{
System.out.println(msg);
}
private int power(int a, int b)
{
return Math.pow(a,b);
}
public class Circle
{
double centerX;
double centerY;
double radius;
public double area()
{
return Math.PI * radius * radius;
}}
Exercise #01:
(Car.java)
Implement a class Car, that has the following characteristics:
a) brandName,
b) priceNew, which represents the price of the car when it was new,
c) color, and
d) odometer.
The class should have:
A. A method getPriceAfterUse() which should return the price of the car after being
used according to the following formula:
car price after being used = priceNew  ( 1 
odemeter
)
600,000
B. A method updateMilage(double traveledDistance) that changes the current state
of the car by increasing its milage, and
C. A method outputDetails() that will output to the screen all the information of the
car, i.e., brand name, price new, price used, color, and odometer.
class car{
String brandname;
double pricenew;
String color;
double odometer;
public static double getPriceAfterUse(double pricenew , double odometer) {
double price_used_car= pricenew*(1-(odometer/600000));
return price_used_car; }
public static void outputDetails(String brandname,double pricenew,String color,double
odometer){
System.out.println(" car model is" + brandname);
System.out.println(" a new car price is= "+ pricenew);
System.out.println(" a car color is " + color);
System.out.println("the car moved distance = " +odometer);
System.out.println("the price of old car = " + getPriceAfterUse(pricenew,odometer)); } }
Exercise #02:
(CarTest.java)
Write a test class for the Car class above. You are required to do the followings:
A. Create an object of type Car.
B. Assign any valid values to the instance variables of the object created in ‘A’.
C. Use the method getPriceAfterUse on the object created in ‘A’ then output the
result to the screen.
D. Use the method updateMilage on the object created in ‘A’ by passing a valid
value.
E. Do part ‘C’ again.
F. Use the method outputDetails on the object created in ‘A’.
class test {
public static void main(String[] args) {
car sss = new car();
double y = sss.getPriceAfterUse(200000.0,400000.900);
System.out.println(" the price after used = " +y);
sss.outputDetails(" IBM" , 200000, "white", 400000.900);
}
}