java phase 1 object oriented programming through java

65
www.esnips.com/user/vapremaims Page 1 OBJECT ORIENTED PROGRAMMING THROUGH JAVA - I JAVA PHASE 1 PROGRAMS Task 1 Your first task is to read the user's name and print it as "Hello <<username>>. Welcome!". Eg: If user's name is Surya; you should be displaying "Hello Surya. Welcome!" // This program read the input from user import java.io.*; class Read { public static void main(String[] args) throws IOException{ InputStreamReader isr=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(isr); //To read the user name System.out.println("Enter the user name"); String name=br.readLine(); System.out.println("Hello "+name); } } Task 1 Output Module 1 Introduction to Java

Upload: premaims

Post on 24-Apr-2015

1.908 views

Category:

Documents


3 download

DESCRIPTION

Help Others and Others will Help You.

TRANSCRIPT

Page 1: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 1

OBJECT ORIENTED PROGRAMMING THROUGH JAVA - I

JAVA PHASE 1 PROGRAMS

Task 1

Your first task is to read the user's name and print it as "Hello <<username>>. Welcome!".

Eg: If user's name is Surya; you should be displaying "Hello Surya. Welcome!"

// This program read the input from user

import java.io.*;

class Read {

public static void main(String[] args) throws IOException{

InputStreamReader isr=new InputStreamReader(System.in);

BufferedReader br=new BufferedReader(isr);

//To read the user name

System.out.println("Enter the user name");

String name=br.readLine();

System.out.println("Hello "+name);

}

}

Task 1 Output Module 1 Introduction to Java

Page 2: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 2

Section 2 Data Types and Operators

Module 1 Tasks

Task 1

Try compiling and running the following code snippets and report on the output and the reason for the output (in .doc or .txt file)

Code snippet 1: int num=2147483647; System.out.println("The number is "+num); num=num+1; System.out.println("The number is "+num); Code snippet 2: float num; System.out.println(num=20); Code snippet 3: int age=24.3; System.out.println("The age is "+age); What can be done to overcome this issue?

class Task1a

{

public static void main(String args[])

{

int num=2147483647;

System.out.println("The number is "+num);

num=num+1;

System.out.println("The number is "+num);

}

}

Task 1 Output Module 1 Section 2 Data Types and Operators

Page 3: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 3

Code snippet 2: float num; System.out.println(num=20);

class Task1c

{

public static void main(String args[])

{

float num;

System.out.println(num=20);

}

}

Task 2 Module 1 Section 2

Code snippet 3: int age=24.3; System.out.println("The age is "+age); What can be done to overcome this issue?

class Task1d

{

public static void main(String args [])

{

int age=24.3; // this is an error

System.out.println("The age is "+age);

}

}

Page 4: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 4

Output

Report on OverCome Issue

This code is not compiled because here floating type value assigned integer variable age so it has given error. To overcome this problem age must be declared as float type (or) integer value is assigned to int type age.

Task 2

You have to extend your first program (Hello world program in previous section) and read in the age and credit card number of the user and print them to the screen. You should store the age and credit card number in appropriate data types.

// To read age and credit number and print in appropriate datatypes

import java.io.*;

class Credit

{

public static void main(String args[]) throws IOException

{

InputStreamReader isr=new InputStreamReader(System.in);

BufferedReader br=new BufferedReader(isr);

System.out.println("Enter age:");

int age=Integer.parseInt(br.readLine());

System.out.println("Enter credit card number:");

int creditno=Integer.parseInt(br.readLine());

System.out.println("Age: "+age);

Page 5: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 5

System.out.println("Credit card number is:"+creditno);

}

}

Task 2 Module 1 Section 2 Data Types and Operators

Page 6: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 6

Module 2

Task 1

Once you have perused the reading material, you can now work on the following task. You will need to provide the output of the following code snippets.

int i=10; System.out.println(i++ +"::"+ ++i); int j=20; int k=30; int l=40; int m=50; int n=60; System.out.println(j+k-l/m*n); boolean result=true; System.out.println(result!=false);

class Module2Task1

{

public static void main(String args[])

{

int i=10;

System.out.println(i++ +"::"+ ++i); //it will print as 10 :: 12

int j=20;

int k=30;

int l=40;

int m=50;

int n=60;

System.out.println(j+k-l/m*n);// it will print as 50

boolean result=true;

System.out.println(result!=false);// it will print as true

}

Page 7: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 7

}

Task 1 Module 2 Section 2 Data Types and Operators

Task 2

You are supposed to find out the area of a circle. You have to read the radius from the user and print the area.

Hint: Area of circle = pi*radius*radius pi=22/7 is a constant Note: We can define constants in Java using the keyword final which you will be introduced to later.

//Area of the circle

import java.io.*;

class Module2Task2

{public static void main(String args[]) throws IOException

{

InputStreamReader isr=new InputStreamReader(System.in);

BufferedReader br=new BufferedReader(isr);

double r;

double area;

double pi;

Page 8: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 8

pi=22.0/7.0;

System.out.println("Enter the area of circle:");

r=Float.parseFloat(br.readLine());

area=pi*r*r;

System.out.println("Area of circle=" +area);

}

}

Task 2 Output Module 2 Section 2 Data Types and Operators

Page 9: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 9

Section 3 Control Statements in Java

Module 1

Task 1

Raju's parents are celebrating their marriage anniversary. They have arranged a small party tonight. They are expecting their colleagues and Raju's friends to attend the party. They have planned to serve 'Coke' and 'Badam Milk' to these guests. But they would like to serve 'Badam Milk' to teenagers and 'Coke' to adults. Please help them in finding teenagers and adults based on age. Write a Java program to find out the adults and teenagers based on their age.

Note: Teenagers are those whose age is between 13 and 19 (both inclusive).

Step by Step guide

Read the age as input from the user Check the age with the conditions mentioned Display the appropriate messages (Eg: Adult or Teenager) and also a message regarding the

drink (Eg: Badam Milk or Coke)

Note: We can come with a condition where some guests are neither teenagers nor adults. What do we do then? Just serve them water and call them Children :-)

//Finding a guest whether guest is adult or teenager or children depending on the age

import java.io.*;

class Teenage

{public static void main(String args[]) throws IOException

{

InputStreamReader isr=new InputStreamReader(System.in);

BufferedReader br=new BufferedReader(isr);

System.out.println("Enter guest age:");

int age=Integer.parseInt(br.readLine());

Page 10: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 10

if(age>=13&&age<=19)

{

System.out.println("Guest is TEENAGER, serve BADAM MILK");

}

else if(age>19)

{

System.out.println("Guest is ADULT, Serve COKE");

}

else

System.out.println("Guest is children, serve water");

}

}

Task 1 Output Module 1 Section 3 Control Statements in Java

Page 11: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 11

Task 2

Your college management is planning to conduct a cricket tournament as part of their college fest and have planned to arrange a digital score board. This digital score board should display greetings/message based on the batsman's score. If the batsman's score is:

>=100 - Message should be displayed "Congratulations on your magnificent century" 80 - 99 - Message should be displayed "If you had played carefully, you would have

seen another milestone in your career" 70 - 79 - Message should be displayed "Good performance, keep it up" 50 - 69 - Message should be displayed "Well played" 10 - 49 - Message should be displayed "Nicely Played but bad luck..." 0 - 9 - Message should be displayed "Oops! hard luck"

//Displaying cricket score board messages depending on the bats man performance

import java.io.*;

class Zerotask

{public static void main(String args[]) throws IOException

{

InputStreamReader isr=new InputStreamReader(System.in);

BufferedReader br=new BufferedReader(isr);

System.out.println("Enter batsman score:");

int score=Integer.parseInt(br.readLine());

if(score>=100)

System.out.println("Congratulations on your magnificent century");

else if(score>=80&&score<=99)

System.out.println("If you had played carefully, you would have seen another milestone in your career");

else if(score>=70&&score<=79)

System.out.println("Good performance, keep it up");

Page 12: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 12

else if(score>=50&&score<=69)

System.out.println("Well played" );

else if(score>=10&&score<=49)

System.out.println("Nicely Played but bad luck..." );

else

System.out.println("Oops! hard luck" );

}

}

Task 2 Output Module 1 Section 3 Control Statements in Java

Page 13: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 13

Additional Task 1

Task 1

Soumit has provided you with three numbers and wants you to find out the largest of these three. Write a program to help him out.

//Finding the largest number of the given three numbers

import java.io.*;

class Additionaltask

{public static void main(String args[]) throws IOException

{

InputStreamReader isr=new InputStreamReader(System.in);

BufferedReader br=new BufferedReader(isr);

System.out.println("Enter number1:");

int n1=Integer.parseInt(br.readLine());

System.out.println("Enter number2:");

int n2=Integer.parseInt(br.readLine());

System.out.println("Enter number3:");

int n3=Integer.parseInt(br.readLine());

if(n1>n2&&n1>n3)

System.out.println("n1 is larger:" +n1);

else if(n2>n1&&n2>n3)

System.out.println("n2 is larger:" +n2);

else

System.out.println("n3 is larger:" +n3);

Page 14: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 14

}

}

Additional Task Output Module 1 Section 3 Control Statementsn in Java

Page 15: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 15

Module 2 Section 3 Control Statements in Java

Module 2

Task 1

Samar your friend has an interesting task for you. He has with him a list of student marks (all marks are out of 100). He now wants to convert these marks from number to word format (i.e. 56 in number format is Fifty six in word format). He knows that you have knowledge of conditional statements and he has approached you to help him. So, now you work on designing a Java program that will help Samar. For simplicity sake, lets assume the following:

Samar enters the marks (in numbers) All marks are integer values only No student gets negative marks No student gets more than 100 marks

import java.io.*;

class Marks

{public static void main(String args[]) throws IOException

{

InputStreamReader isr=new InputStreamReader(System.in);

BufferedReader br=new BufferedReader(isr);

System.out.println("Enter student marks:");

int m=Integer.parseInt(br.readLine());

if(m==0)

Page 16: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 16

System.out.println("Zero");

else if(m==1)

System.out.println("one");

else if(m==2)

System.out.println("two");

else if(m==3)

System.out.println("three");

else if(m==4)

System.out.println("four");

else if(m==5)

System.out.println("five");

else if(m==6)

System.out.println("six");

else if(m==7)

System.out.println("seven");

else if(m==8)

System.out.println("eight");

else if(m==9)

System.out.println("nine");

else if(m==10)

System.out.println("ten");

else if(m==11)

System.out.println("eleven");

else if(m==12)

System.out.println("twelve");

Page 17: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 17

else if(m==13)

System.out.println("thirteen");

else if(m==14)

System.out.println("fourteen");

else if(m==15)

System.out.println("fifteen");

else if(m==16)

System.out.println("sixteen");

else if(m==17)

System.out.println("seventeen");

else if(m==18)

System.out.println("Eighteen");

else if(m==19)

System.out.println("Ninteen");

else if(m==20)

System.out.println("twenty");

else if(m==100)

System.out.println("hundread");

else{

int x=m/10;

switch(x)

{

case 2:System.out.print("Twenty");

break;

case 3:System.out.print("Thirty");

Page 18: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 18

break;

case 4:System.out.print("Fourty");

break;

case 5:System.out.print("fifty");

break;

case 6:System.out.print("Sixty");

break;

case 7:System.out.print("seventy");

break;

case 8:System.out.print("eighty");

break;

case 9:System.out.print("Ninty");

break;

}

int y=m%10;

switch(y)

{case 1:System.out.print(" one");

break;

case 2:System.out.print(" two");

break;

case 3:System.out.print(" three");

break;

case 4:System.out.print(" four");

break;

Page 19: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 19

case 5:System.out.print(" five");

break;

case 6:System.out.print(" six");

break;

case 7:System.out.print(" seven");

break;

case 8:System.out.print(" eight");

break;

case 9:System.out.println(" nine");

break;

}

}

}

}

Task 1 Output Module 2 Section 3 Control Statements in Java

Page 20: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 20

Task 2

You need to implement the calculator functionality in Java. You will need to give an option for the user to perform different functions like "Addition", "Subtraction", "Multiplication" and "Division". Please note that the user will be able to perform only one operation from the above mentioned operations. Hint: Use switch-case and if-then-else conditions

In the next module you will be introduced to "Loops" wherein you will learn how to perform repetitive operations. So, save this program in a location from where you can retrieve it later.

import java.io.*;

class Calculator

{public static void main(String args[]) throws IOException

{

InputStreamReader isr=new InputStreamReader(System.in);

BufferedReader br=new BufferedReader(isr);

System.out.println("1.ADDITION");

System.out.println("2.SUBTRACTION");

System.out.println("3.MULTPLICATION");

System.out.println("4.DIVISION");

System.out.println("Enter your choice");

int c=Integer.parseInt(br.readLine());

System.out.println("Enter the value of a:");

int a=Integer.parseInt(br.readLine());

System.out.println("Enter the value of b:");

int b=Integer.parseInt(br.readLine());

int d;

switch(c)

{

case 1: d=a+b;

System.out.println("Addition is:"+d);

break;

Page 21: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 21

case 2: d=a-b;

System.out.println("Subtraction:"+d);

break;

case 3: d=a*b;

System.out.println("Multiplication:"+d);

break;

case 4: d=a/b;

System.out.println("Division:"+d);

break;

default: System.out.println("Invalid choice");

break;

}

}

}

Task 2 Output Module 2 Section 3 Control Statements in Java

Page 22: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 22

Module 3 Section 3

Task 1

Write a program that prints the first 50 UGLY numbers. Note: Ugly numbers are numbers whose only prime factors are 2, 3 or 5. For example 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15,…… are ugly numbers. By convention, 1 is considered as an ugly number. You can use any one of the iterative statements

class Ugly

{

public static void main(String[] args)

{

int c=0;

int i=1;

System.out.println("1");

while(c<=50)

{

if(i%2==0||i%3==0||i%5==0)

{

System.out.println(i );

c=c+1;

}

i=i+1;

}

}

}

Page 23: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 23

Task 1 Output Module 3 Section 3 Control Statements in Java

Page 24: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 24

Additional Tasks

Write a program to print the multiplication table (till 20) of a given number.

Eg: If number is 2 Output should be: 2*1 = 2 2*2 = 4 . . . 2*20 =40

import java.io.*;

class Multi

{

public static void main(String args[]) throws IOException

{

InputStreamReader isr=new InputStreamReader(System.in);

BufferedReader br=new BufferedReader(isr);

System.out.println("Enter number;");

int n=Integer.parseInt(br.readLine());

int i=1;

int r;

while(i<=20)

{

r=n*i;

System.out.println(n+ "*" +i +"=" +r);

i=i+1;

}

}

}

Page 25: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 25

Additional Task Output Module 3 Sectio 3 Control Statements in Java

Page 26: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 26

Module 4 Section 3 Control Statements in Java

Task 1

Write a calculator program using switch-case (you can use the already designed program in the previous section). The program should provide 4 operations - add, subtract, multiply and divide - and ask the user to select an option. The program should perform the operation selected by user and display the result. If user selects an option other than the options specified, a default error message should be displayed that the option selected does not exist. The program should take in user input till the user types in 'q' as an option.[Once user types in 'q', the program should quit].

import java.io.*;

class Cal2

{

public static void main(String args[]) throws IOException

{

int c;

InputStreamReader isr=new InputStreamReader(System.in);

BufferedReader br=new BufferedReader(isr);

do

{

System.out.println("1.ADDITION");

System.out.println("2.SUBTRACTION");

System.out.println("3.MULTPLICATION");

System.out.println("4.DIVISION");

System.out.println("5.EXIT");

System.out.println("Enter your choice");

c=Integer.parseInt(br.readLine());

Page 27: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 27

System.out.println("Enter the value of a:");

int a=Integer.parseInt(br.readLine());

System.out.println("Enter the value of b:");

int b=Integer.parseInt(br.readLine());

int d;

switch(c)

{

case 1: d=a+b;

System.out.println("Addition is:"+d);

break;

case 2: d=a-b;

System.out.println("Subtraction:"+d);

break;

case 3: d=a*b;

System.out.println("Multiplication:"+d);

break;

case 4: d=a/b;

System.out.println("Division:"+d);

break;

case 5:break;

default: System.out.println("Invalid choice");

break;

}

}while(c!=5);

}

}

Page 28: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 28

Task 1 Output Module 4 Section 3 Control Statements in Java

Page 29: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 29

Task 2

Samar again comes to you with a problem.

Problem statement: My teacher has asked me come with a list of numbers that are the sum of their own digits to the power of the number of digits. I am totally clueless on how to proceed. To make things easy, my teacher has provided me with an example of such a number.

Eg1 : Lets consider the number 153 Number of digits in 153 is 3 We can see that 153 = 13 + 53 + 33 Thus 153 is one such number that is the sum of its own digits to the power of the number of digits. Eg2: Lets consider the number 1634. Number of digits is 4 We can see that 1634 = 14 + 64 + 34 + 44 Thus 1634 is one such a number that is the sum of its own digits to the power of the number of digits.

My teacher has also told me that such numbers are referred to as Armstrong numbers. I am supposed to come with the list of all such numbers below 1,000,000. Boss! please help me.

import java.io.*;

class Teach

{

public static void main(String args[]) throws IOException

{

InputStreamReader isr=new InputStreamReader(System.in);

BufferedReader br=new BufferedReader(isr);

System.out.println("Enter the number:");

int n=Integer.parseInt(br.readLine());

int a;

a=n;

int c=0;

while(n>0)

Page 30: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 30

{

n=n/10;

c=c+1;

}

System.out.println("The no of digits in the given number:"+c);

int sum=0;

int p=1;

int b;

while(a>0)

{

b=a%10;

p=1;

int i=1;

while(i<=c)

{

p=p*b;

i=i+1;

}

sum=sum+p;

a=a/10;

}

System.out.println("The Result: "+sum);

}

}

Page 31: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 31

Task 2 Output Module 4 Section 3 Control Statements in Java

Page 32: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 32

Additional Tasks 1

Write a program to find out all the leap years between 1947 and 2050.

class Addi1

{

public static void main(String args[]) {

int l=1947;

int u=2050;

while(l<=u)

{

if(l%4==0)

{

System.out.println(l + " Is a leap year");

}

l=l+1;

}

}

}

Page 33: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 33

Additional Task1 Output Module 4 Section 3 Control Statements in Java

Page 34: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 34

Additional Tasks 2

Write a program to find out the factorial of a number. Factorial of a number is the product of all numbers less than and equal to that number.

Eg: Factorial of 5 = 5*4*3*2*1 = 120

import java.io.*;

class Addi2

{

public static void main(String args[]) throws IOException

{

InputStreamReader isr=new InputStreamReader(System.in);

BufferedReader br=new BufferedReader(isr);

System.out.println("Enter the number");

int n=Integer.parseInt(br.readLine());

int i=1;

int fact=1;

while(i<=n)

{

fact=fact*i;

i=i+1;

}

System.out.println("Factorial "+fact);

}

}

Page 35: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 35

Additional Task 2 Output Module 3 Control Statements in Java

Page 36: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 36

Object Oriented Programming Section 4

Module 1

Task 1

Your old friend who is working in the admissions department of your college comes to you with a problem.

ProblemStatement: I am in charge for the students admissions every year. I now want to computerise this admission process and want you to help me in this regard. Create an application that would allow me to do the following:

Create a student record Display the student record Remove the student record

Consider only the student's name and age when creating a student record (for now).

Note: You will be creating only one student record in this case. In the next section, you will know how to create more records (an array of records/objects).

import java.io.*;

import java.util.*;

class Student1

{

String Sname;

String Grp;

String Sex;

String Age;

Student1()throws IOException

{

BufferedReaderbr= new BufferedReader(new InputStreamReader(System.in));

System.out.print("\nEnter Student name : ");

Sname=br.readLine();

Page 37: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 37

System.out.print("\nEnter Grp : ");

Grp=br.readLine();

System.out.print("\nEnter Sex : ");

Sex=br.readLine();

System.out.print("\nEnter Age : ");

Age=br.readLine();

}

public void disdetails()

{

System.out.println("Student Name:"+Sname);

System.out.println("Student Grp:"+Grp);

System.out.println("Student Sex:"+Sex);

System.out.println("Student Age:"+Age);

}

public void removedetails()

{

}

}

class Student

{

public static void main(String[] args) throws IOException

{

Student1 s=new Student1();

s.disdetails();

s.removedetails();

}

Page 38: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 38

}

Task 1 Output Module 1 Section 4 OOPS - I

Page 39: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 39

Task 2

In this task, we will introduce you to the Java API (Please right click on this link and open in a new window/tab).

You can see that the Java API contains all the classes available in the Java language. The API gives you a snapshot of the classes and the methods in them.

Your task is to generate a list of 10 random numbers and print them.

Hint: Which class in the API would you use to generate the random numbers? We have provided you a hint in the question itself :-)

import java.util.*;

public class RandomNumberGenerator {

public static void main(String[] args) {

Random rand = new Random (1);

for(int i=0; i<10; i++) {

System.out.println(rand.nextInt());

}

}

}

Task 2 Output Module 1 Section 4 OOPS - I

Page 40: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 40

Module 2 Section 4 Object Oriented Programming Phase 1

Task 1

Create a class Clock that has the following attributes:

Hour (integer) Minutes (integer) Seconds (integer) isAM (boolean) - true if time is before 12:00 Noon and false if time is after 12:00

Noon

These attributes are represented by data fields. Class Clock should contain the following constructors:

no parameters (sets clock to midnight) all attributes specified (hour, minute, second, isAM)

Class Clock supports the following public methods:

getHours() - returns the Hours getMinutes() - returns the Minutes getSeconds() - returns the Seconds getIsAM() - returns AM status

Class Clock also supports a setTime() method that reads all four attributes from user.

Note: Take the following into consideration

The time is in 12 hour format (So isAM needs to be taken from user). The user may or may not set the time at runtime (i.e. user may or may not enter

argument values) o In this case the setTime() method should be invoked to read the time.

Page 41: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 41

Additional Tasks

Task 1

Implement the complex number class. At a minimum it should have a constructor,and methods to add, subtract, and multiply two complex numbers, and to return the real and imaginary parts. (complex number = x + iy)

Hint: Ask user to input real and imaginary part individually

For example: Suppose the two imaginary numbers are 2+5i and 6-3i, you should be taking input as follows

Enter the real part of the first number (a): 2

Enter the imaginary part of the first number (b): 5

Enter the real part of the second number (c): 6

Enter the imaginary part of the second number (d): -3

Now perform addition, subtraction and multiplication operations on these two complex numbers.

public class Complex {

int x;

int y;

public Complex (int x, int y) {

this.x = x;

this.y = y;

}

public Complex(){

}

public Complex addComplex(Complex a) {

Complex c = new Complex();

c.x = this.x + a.x;

Page 42: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 42

c.y = this.y + a.y;

return c;

}

public Complex subtractComplex(Complex a) {

Complex c = new Complex();

c.x = this.x - a.x;

c.y = this.y - a.y;

return c;

}

public Complex multiplyComplex(Complex b){

Complex c = new Complex();

c.x = this.x * b.x - this.y * b.y;

c.y = this.x * b.y + this.y * b.x;

return c;

}

public void printComplex(){

System.out.println(this.x+" i "+this.y);

}

public static void main(String[] args) {

Complex a = new Complex(5,4);

Complex b = new Complex(5,3);

Complex c=a.addComplex(b);

c.printComplex();

c=a.subtractComplex(b);

c.printComplex();

c=a.multiplyComplex(b);

c.printComplex();

Page 43: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 43

}

}

Additional Task OutputModule 2 Section 4 OOPS - I

Page 44: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 44

Section 5 Java Coding Standards

Module 1

No Tasks in this Module

Page 45: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 45

Section 6 Arrays in Java OOPS JAVA Phase 1

Module 1

Task 1

Write a program to generate 10 random numbers and store it in a array. Display the maximum and minimum numbers in the array.

Note: You have worked on generating the random numbers. you can use the same program

import java.util.*;

class Task1

{

public static void main(String args[])

{int i=0;

int a[]=new int[11];

Random r=new Random();

System.out.println("the 10 random numbers are");

while(i<10)

{

a[i]=(r.nextInt(100));

System.out.println(+a[i]);

i=i+1;

}

Arrays.sort(a);

System.out.println("The Minimum value in the array:"+a[1]);

Page 46: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 46

System.out.println("The Maximum value in the array:"+a[a.length-1]);

}

}

Task 1 Output Section 6 Arrays in Java OOPS JAVA Phase 1

Page 47: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 47

Task2: Sudoku Checker

Mr. Varun is running an online gaming website. He initially started his site by putting Sudoku puzzles. He want you to write a program to check whether the answer to the puzzle is correct or not.

To make things easy, initialize your 2D array with the data given below.

Sudoko: Given a 9-by-9 array of integers between 1 and 9, check if it is a valid solution to a Sudoku puzzle: each row, column, and block should contain the 1 to 9 integers exactly once.

5 3 4 | 6 7 8 | 9 1 2 6 7 2 | 1 9 5 | 3 4 8 1 9 8 | 3 4 2 | 5 6 7 -------+-------+------ 8 5 9 | 7 6 1 | 4 2 3 4 2 6 | 8 5 3 | 7 9 1 7 1 3 | 9 2 4 | 8 5 6 -------+-------+------ 9 6 1 | 5 3 7 | 2 8 4 2 8 7 | 4 1 9 | 6 3 5 3 4 5 | 2 8 6 | 1 7 9

import java.util.*;

import java.io.*;

public class Sudoku

{

public static void main(String arg[]) throws IOException

{

int[][] sudo={{5,3,4,6,7,8,9,1,2},

{6,7,2,1,9,5,3,4,8},

{1,9,8,3,4,2,5,6,7},

{8,5,9,7,6,1,4,2,3},

{4,2,6,8,5,3,7,9,1},

{7,1,3,9,2,4,8,5,6},

{9,6,1,5,3,7,2,8,4},

Page 48: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 48

{2,8,7,4,1,9,6,3,5},

{3,4,5,2,8,6,1,7,9}};

int[][] checker={{1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 },

{1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 },

{1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 },

{1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 },

{1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 },

{1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 },

{1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 },

{1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 },

{1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 }};

int[][] sudo1=new int[9][9];

int[][] sudo2=new int[9][9];

int[] a=new int[9];

int i,j,flag=0;

//DataInputStream dis=new DataInputStream(System.in);

//System.out.println("Enter the 2D array elements:");

for(i=0;i<9;i++)

{

for(j=0;j<9;j++)

{

//System.out.println("sudo["+i+"]["+j+"]");

//sudo[i][j]=Integer.parseInt(dis.readLine());

sudo1[i][j]=sudo[i][j];

}

}

Page 49: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 49

for(i=0;i<9;i++)

{

for(j=0;j<9;j++)

{

System.out.print(sudo1[i][j]+" ");

}

System.out.print("\n");

}

for(i=0;i<9;i++)

{

Arrays.sort(sudo1[i]);

}

/*System.out.println("Rows altered to column matrix:");

for(i=0;i<9;i++)

{

for(j=0;j<9;j++)

{

a[i]=sudo[j][i];

sudo2[i][j]=a[i];

System.out.print(sudo2[i][j]+" ");

}

System.out.println();

}*/

//Trnspose

for(i=0;i<9;i++)

{

Page 50: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 50

for(j=0;j<9;j++)

{

sudo2[i][j]=sudo[j][i];

}

}

/*System.out.println("Transpose Matrix:");

for(i=0;i<9;i++)

{

for(j=0;j<9;j++)

{

System.out.print(sudo2[i][j]+" ");

}

System.out.println();

}*/

for(i=0;i<9;i++)

{

Arrays.sort(sudo2[i]);

}

/*System.out.println("Rows sorted matrix:");

for(i=0;i<9;i++)

{

for(j=0;j<9;j++)

{

System.out.print(sudo1[i][j]+" ");

}

System.out.print("\n");

}

Page 51: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 51

System.out.println("Columns sorted matrix:");

for(i=0;i<9;i++)

{

for(j=0;j<9;j++)

{

System.out.print(sudo2[i][j]+" ");

}

System.out.print("\n");

}*/

for(i=0;i<9;i++)

{

for(j=0;j<9;j++)

{

if((sudo1[i][j]==checker[i][j])&&(sudo2[i][j]==checker[i][j]))

flag=0;

else

{

flag=1;

break;

}

}

if(flag==1)

break;

}

// Checking of blocks

int z[] = new int[9];

Page 52: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 52

for(i=0; i<3; i++)

{

for(j=0; j<3; j++)

{

int rowbeg = 3 * i;

int rowend = 3*i + 2;

int colbeg = j * 3;

int colend = j * 3 + 2;

for(int k=0; k<9; k++)

{

z[k]=0;

}

for(int k=3*i; k<= 3*i+2; k++)

{

for(int l = 3*j ; l <= 3*j+2; l++)

{

z[sudo[k][l]-1]++;

if(z[sudo[k][l]-1] > 1)

{

flag = 1;

break;

}

}

}

}

}

Page 53: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 53

if(flag==1)

System.out.println("Not a Correct Answer");

else

System.out.println("Correct answer");

}

}

Task 2 Output Module 1 Section 6

Page 54: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 54

Module 7Strings in Java

Module 1

Task 1

Create a class that reverses the order of words to a given string or sentence. For example if we give

Sample input: "who am i"

Sample output: "i am who"

import java.io.*;

import java.util.*;

class Stringreverse

{

public static void main(String arg[])

{

Scanner s=new Scanner(System.in);

System.out.println("Enter the Input String:");

String str=s.nextLine();

Stack<String> stack=new Stack<String>();

String[] temp;

String delimiter=" ";

temp=str.split(delimiter);

for(int i=0;i<temp.length;i++)

{

stack.push(temp[i]);

}

System.out.println("Original string is-->"+str);

Page 55: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 55

System.out.println("Reverse Word String is--->");

while(!stack.empty())

{

String rev=stack.pop();

System.out.print(rev);

System.out.print(" ");

}

}

}

Task 1 Output Module 1 Section 7 Strings in Java Phase 1

Page 56: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 56

Task 2

Write a program to develop a menu of String operations like the program should provide 5 operations(uppercase, lowercase, display each word, search for a substring, replace white space with $ symbol)

Take the string(more than 3 words) and choice of user as input and the program should perform the operation selected by user and display the result.

Hint: Use Java API to solve this problem

Sample Test case: Enter string of your choice: "Welcome to object oriented programming in java"

---String Operations Menu--- 1. Convert to UpperCase 2. Convert to LowerCase 3. Display each word in the string 4. Search for a substring 5. Replace all the white spaces in the string with $ symbol Enter your choice: 1 Output: WELCOME TO OBEJCT ORIENTED PROGRAMMING IN JAVA Enter your choice: 2 Output:"welcome to object oriented programming in java" Enter your choice: 3 Output: welcome to object oriented programming in java Enter your choice: 4 Enter your key to search: "object" Output: "Key found" Enter your choice: 5 Output: "welcome$to$object$oriented$programming$in$java"

import java.io.*;

import java.util.*;

class Stringoperation

{

public static void main(String arg[])

{

//BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

Page 57: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 57

Scanner s=new Scanner(System.in);

System.out.println("Enter Input String:");

String s1=s.nextLine();

//String s1=br.readLine();

//StringBuffer s1=new StringBuffer();

do

{

System.out.println(" 1.UpperCase \n 2.Lowecase \n 3. Display each Word \n 4.substring \n 5. Repalce white space wiht $ symbol \n 6.Exit");

System.out.println("Enter your choice");

int ch=s.nextInt();

switch(ch)

{

case 1: String str1=s1.toUpperCase();

System.out.println(str1);

break;

case 2:

str1=s1.toLowerCase();

System.out.println(str1);

break;

case 3:

Stack<String> stack=new Stack<String>();

String[] temp;

String delimiter=" ";

temp=s1.split(delimiter);

for(int i=0;i<temp.length;i++)

Page 58: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 58

{

System.out.println(stack.push(temp[i]));

}

break;

case 4: System.out.println("Enter startind position");

int a=s.nextInt();

System.out.println("Enter ending position");

int b=s.nextInt();

System.out.println(s1.substring(a,b));

break;

case 5:

System.out.println(s1.replace(' ','$'));

break;

case 6: System.exit(0);

}

}while (true);

}

}

Page 59: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 59

Task 2 Output Module 1 Section 7 Strings in Java Phase 1

Page 60: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 60

Module 2 Section 7 Strings in Java

Task 1

Write a program to encrypt a message that your boss is sending to a client. And decrypt that message after the client is received using the following algorithm

To make it simple, take a message (string of words, atleast 3), key as input and print the encrypted and decrypted messages.

Step-by-step guide

Shuffle the words in the message(say 1st word appears in the last and so on)

ex: msg: "Welcome to java programming" shuffle as "programming java to welcome"

Take the Key from the user as input and encrypt by the shifting the alphabets according to the key

ex: msg: "java" key = 2 then the msg: "lcxc"

import java.util.*;

class abc

{

String str="";

String str1="";

String str2=" ";

String str3=" ";

int key=0;

int temp=0;

Scanner s2=new Scanner(System.in);

public void e()

{

System.out.print("Enter the input string:");

Page 61: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 61

str1=s2.nextLine();

System.out.print("Enter key value");

key=s2.nextInt();

Stack<String> stack=new Stack<String>();

String[] temp1;

String delimiter=" ";

temp1=str1.split(delimiter);

for(int i=0;i<temp1.length;i++)

{

stack.push(temp1[i]);

}

while(!stack.empty())

{

str=stack.pop();

for (int i = 0; i < str.length(); i ++)

{

char ch = str.charAt(i);

int c=(int)(ch);

if(c>96 && c<123)

{

str2+= (char)(97 + ((c -97)+ key) % 26);

}

else if(c>64 && c<91)

{

str2+= (char)(65 + ((c -65)+ key) % 26);

}

Page 62: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 62

else str2+=ch; }

str2+=" ";

}

System.out.println(" "+str2);

temp=1;

}

public void d()

{

if(temp==1)

{

Stack<String> stack1=new Stack<String>();

String[] temp11;

String delimiter1=" ";

temp11=str2.split(delimiter1);

for(int i=0;i<temp11.length;i++)

{

stack1.push(temp11[i]);

}

while(!stack1.empty())

{

str=stack1.pop();

for (int i = 0; i < str.length(); i ++)

{

char ch = str.charAt(i);

int c=(int)(ch);

if(c>96 && c<123)

Page 63: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 63

{

str3+= (char)(97 + ((c -97)- key) % 26);

//str3[i]=str3[i] + (char)(97 + ((c -97)- key) % 26);

}

else if(c>64 && c<91)

{

str3+= (char)(65 + ((c +65)- key) % 26);

//str3[i]=str3[i] + (char)(65 + ((c +65)- key) % 26);

}

else str3+=ch;

//else str3[i]=str3[i]+ch;

}

str3+=" ";

}

System.out.println(" "+str3);

}

else System.out.println("There is not message to Decrypt");

temp=0;

}

}

class EncrDecrUsingObject

{

public static void main(String[] args)

{

Scanner s1=new Scanner(System.in);

int cho;

abc b=new abc();

Page 64: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 64

do

{

System.out.print("1.Encrypt\n2.Decrypt\n3.Exit \nEnter ur choice:");

cho=s1.nextInt();

switch(cho)

{

case 1: b.e();

break;

case 2: b.d();

break;

case 3: System.exit(0);

}

}

while (true);

}

}

Task 1 OutputModule 2 Section 7 Strings in Java Phase 1

Page 65: Java Phase 1 Object Oriented Programming Through Java

www.esnips.com/user/vapremaims Page 65