Ctood Assignment2
Ctood Assignment2
Class diagram 2M
Demo
+convertToFeet(meters:double):doubl
e
+main(args: String[]):void
Code: 2.5M
import java.util.Scanner;
publicclassDemo {
publicstaticdouble convertToFeet(doublemeters)
{
returnmeters*3.2786;
}
publicstaticvoid main(String[] args)
{
Scanner sc=new Scanner(System.in);
doublemeters=sc.nextDouble();
System.out.printf(" meters in feet = %.2f", convertToFeet(meters));
Output:
12
meters in feet = 39.34
(or)
2. Illustrate the differences between static and instance members of class 4.5
Marks
3. Draw the class diagram and code the logic to read a set of integers from a file and count
the number of even and odd numbers. Display the output on console.
8M
Class diagram
2M
Demo
+main(args: String[]):void
Program:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
publicclass ReadFromFile {
Student
-Id:int
-Name:String
-Mobile:long
+setId(id:int):void
+setName(name:String):void
+setMobile(mobile:long):void
+getId():int
+getName():String
+getMobile():long
+ display():void
Fig: Class diagram
Code:
package p1;
import java.util.Scanner;
class Student
{
private int id;
private String name;
private long mobile;
public void setId(int id)
{
this.id=id;
}
public void setName(String name)
{
this.name=name;
}
public void setMobile(long mobile)
{
this.mobile=mobile;
}
void int getId()
{
return id;
}
void String getName()
{
return name;
}
void long getMobile()
{
return mobile;
}
void display()
{
System.out.println(“ID: ”+getId()+”Name: ”+getName()+”Mobile:
”+getMobile());
}
public static void main(Sting args[])
{
Student s1=new Student();
Scanner sc=new Scanner(System.in);
System.out.println(“Enter Id,name and mobile number”);
s1.setId(sc.nextInt());
s1.setName(sc.next());
s1.setMobile(sc.nextLong());
s1.display();
}
}
5. Design a class BMI as per the class diagram. Enhance the design by modularizing to
package level. The formula for BMI (Body Mass Index) is weight in kilograms divided by
height in meters squared. The data must be printed in the following format. NAME: ABC
HEIGHT: 1.65 WEIGHT: 70 BMI: 25.7. Develop the main in Demo class to test the
capabilities of the above BMI class. 12.5M
BMI
-name: String
-height: double
-weight: double
Code:
package p1;
class BMI
8M
{
private String name;
privatedoubleheight, weight;
publicvoid setData(String n, doubleh, doublew)
{
name=n;
height=h;
weight=w;
}
publicdouble computeBMI()
{
returnweight/(height*height);
}
public String toString()
{
return String.format("NAME: %s HEIGHT: %.2f WEIGHT: %.0f BMI: %.2f
",name,height,weight,computeBMI());
}
}
publicclass Demo {
4.5M
publicstaticvoid main(String args[]) {
BMI ob = new BMI();
ob.setData("ABC",1.65,70);
System.out.println(ob);
}
}
6. The supervisor of a movie theatre decides to automate Ticket Booking. The task
is to develop a class Ticket with TicketID, number of seats, date and fare as
instance data members and a static fields totalSeatsBooked and
totalTicketsBooked. Write getters and setters. Draw the class diagram and a
TicketDemo class to create object and access Ticket class methods. (Input data to
be read from console.)
12.5M
package stringmethod;
import java.util.Scanner; // Class Diagram 4M
public class TicketDemo // 3.5M for Demo class
{
public static void main(String[] args)
{
Ticket obj=new Ticket();
Scanner s=new Scanner(System.in);
System.out.println("Enter the TicketId:");
long a=s.nextLong();
obj.setId(a);
System.out.println("Enter the number of Seats:");
int b=s.nextInt();
obj.setSeats(b);
System.out.println("Enter the Fare:");
long d=s.nextLong();
obj.setFare(d);
System.out.println("Enter the Date:");
String c=s.next();
obj.setDate(c);
Ticket.totalTicketsBooked=1;
Ticket.totalSeatsBooked=obj.getSeats();
String cc=obj.getDate();
long dd=obj.getFare();
System.out.println("Total Tickets
Booked="+Ticket.totalTicketsBooked);
System.out.println("Total Seats
Booked="+Ticket.totalSeatsBooked);
System.out.println("Total Fare="+(obj.getSeats()*dd));
System.out.println("DATE="+cc);
s.close();
}
}
---------------------------------------------------
package Stringmethod;
public class Ticket
{
private long TicketID;
private int no_of_seat;
private String date;
private long fare;
static long totalSeatsBooked;
static long totalTicketsBooked;
void setId(long id)
{
TicketID=id;
}
void setSeats(int seat)
{
no_of_seat=seat;
}
void setDate(String dat)5M
{
date=dat;
}
void setFare(long rate) {
fare=rate;
}
long getId()
{
return TicketID;
}
int getSeats()
{
return no_of_seat;
}
String getDate()
{
return date;
}
long getFare()
{
return fare;
}
}
7. Suppose that s1, s2, and s3 are three strings, given as follows:
4.5M
What are the results of the following expressions? Justify your answer
A separated memory is allocated for data which is not same in string pool.Here == compares the
memory location address stored in s1,s2,s3. Since the data in s1,s2 and s2,s3 are not same, a
separate memory is allocated in string pool which have different addresses. Hence a) and b) are
false.
equals function compares the data present in s1, s2 and s1, s3 in c) and d)
compareTo returns the ascii difference of the first character differing in s1, s2 and s2, s3 in e)
and f)
Q8) Assume a class Book with the following attributes – ISBN (long), Title (String),
Price(double), Year (integer). Write the parameterized constructor with 4 arguments
and draw the class diagram. Class Diagram-> 2.5M
Book
+ ISBN: long
+ Title: String
+ Price: double
+ Year: int
Book(i:long,t:String,p:double,y:int)
Book(long i, String t, double p, int y)
{
ISBN=i;
Title= t; -> 2M
Price= p;
Year= y;
}
Q9) Modularize to package level and draw the class diagram to develop a class called Date that
includes a month(type int), a day(type int) and a year(type int). The class should have a
parameterized constructor that initializes 3 instance variables. Provide a method toString() that
displays the month, day and year separated by forward slashes (/). Write a test application named
DateTest that demonstrates class Date’s capabilities. 8M
Class Diagram : 4M
package p1
DateClass
-day: int
-month:int
-year:int
+toString():String
package p2
Test
+main(args: String[]):void
Code: 4M
package p1;
publicclass DateClass
{
privateintday, month, year;
publicString toString() {
returnday + "/" + month + "/" + year ;
}
package p2;
importp1.DateClass;
publicclass Test {
Q10) Some websites impose certain rules for passwords. Suppose the password rules are
as
follows: ¦ A password must have at least eight characters. ¦ A password consists of only
letters and digits. Write main () method that prompts the user to enter a password and
a static methodisValidPassword() that expects a string argument and returns boolean
type aftervalidating the password.
import java.util.Scanner;
class Password
{
String pass;
staticbooleanisValidPassword(String p)
{
if((p.length()>=8) &&p.matches(".*[a-zA-Z].*") &&p.matches(".*[0-9].*"))
{
return true;
}3M
else
{ return false; }
}
}
public class Passwordrule
{
public static void main(String[] args)
{
String pas;
Scanner s=new Scanner(System.in);
System.out.println("Enter the password");
pas=s.next();
boolean res=Password.isValidPassword(pas);
if(res==true)2M
{
System.out.println("password is valid");
}
else
{
System.out.println("password is invalid");
}
}
}
11. Draw the class diagram modularized to package level and develop a class “Dictionary” that
contains the following information (a) Name of a person (b) mobile number (both as private
attributes). The main() demo class must be able to store details of 10 person and display a menu
with the following options. 1. Add new person information 2. Display all data.
package esan;
publicclass Dictionary {
private String name;
privatelongmob;
publicDictionary(String name,longmob){
this.name=name;
this.mob=mob;
}
public String toString() {
return"Name="+name+" Mobile No="+mob+" \n";
}
}
package tgan;
import java.util.Scanner;
import esan.Dictionary;
publicclass DictionaryDemo {
publicstaticvoid main(String[] args) {
Dictionary[] d=new Dictionary[10];
Scanner sc=new Scanner(System.in);
intsize=0;
booleanrepeat=true;
while(repeat) {
System.out.println("1. addNewPerson\n2.Display\n others
exit");
intoption=sc.nextInt();
switch(option)
{
case 1:
d[size]=new Dictionary(sc.next(),sc.nextLong());
size++;
break;
case 2:
for(inti=0;i<size;i++)
System.out.println(d[i]);
break;
default:
repeat=false;
}
}
sc.close();
}
Q12) The Election commission requires the following task to be done. Draw the class diagram
modularized to package level and code the following specifications: A class Voter with ID, name and
age as private attributes. Write Constructor, toString() method. The VoterDemo has main() method
which reads and stores data of 10 voters and display a menu with following operations
12.5M
Code:
package p1;
publicclass Voter
4.5
{
privatelongid;
private String name;
privateintage;
public Voter(longid, String name, intage) {
this.id = id;
this.name = name;
this.age = age;
}
publiclong getId()
{
returnid;
}
public String toString() {
return"id=" + id + ", name=" + name + ", age=" + age;
}
}
package p2;
import java.util.Scanner;
import p1.Voter;
publicclass VoterDemo 8M
{
publicstaticvoid Search(Voter ob[], longkey, intnov)
{
for(inti=0;i<nov;i++)
{
if(ob[i].getId() == key)
{
System.out.println(ob[i]);
return;
}
}
System.out.println(" Voter id not found");
}
publicstaticvoid main(String[] args) {
Scanner sc = new Scanner(System.in);
Voter ob[]=new Voter[10];
intnov=0;
while(true)
{
System.out.println("Enter 1. 1. Add new Voter 2. Search Voter
based on id");
intchoice=sc.nextInt();
switch(choice)
{
case 1:
System.out.println("enter voter id, name and
age");
ob[nov]=new
Voter(sc.nextLong(),sc.next(),sc.nextInt());
nov=nov+1;
break;
case 2:
System.out.println("enter the voter id to be
searched");
longkey=sc.nextLong();
Search(ob,key,nov);
break;
default: return;
}
}
}
}
Koneru Lakshmaiah Education Foundation
Academic year: 2019-2020
Sem-In Examinations-I,
Answer Key
Part-A ( 4 x 3 marks = 12 marks )
1) Given the lengths of 2 sides of a right-angled triangle through console, write a java
program to print the length hypotenuse. (Hypotenuse = (side12 + side2 )1/2 )
package p1;
importjava.util.Scanner;
public class Triangle {
2) The marks of students in a class are specified as command line arguments, the task is
finding the maximum and average of the marks. Write a program to perform the above
task.
public class Marks {
6)The Course class has the following private fields: courseCode, courseTitle (both of
type String) and credits (type int). It also contains assessors and mutators for each
attribute.
1. courseCode must have 6 characters (only digits and characters)
2. Credits must be a positive value less than 6.
Also code the toString( ) method to display the data of courses and draw the class
diagram.
Class Diagram
P1
Course
- courseCode : String
- courseTitle : String
- credits : int
- getCourseCode():String
- getCourseTitle():String
- getCredits(): int
- setCourseCode(c:String):boolean
- setCourseTitle(t:String): Boolean
- setCredits(cre:int): Boolean
+ toString():String
-setCourse(t:String, c:String, cre:int): void
+ main(args[] : String) : void
Program
package p1;
importjava.util.regex.Matcher;
importjava.util.regex.Pattern;
privateintgetCredits()
{
returnthis.credits;
}
privatebooleansetCourseCode(String c)
{
int cc=c.length();
Pattern p=Pattern.compile("[^A-Za-z0-9]*");
Matcher m=p.matcher(c);
boolean b=m.find();
if(cc==6 && b)
{
return true;
}
return false;
}
privatebooleansetCourseTitle(String t)
{
Pattern p=Pattern.compile("[^A-Za-z]");
Matcher m=p.matcher(t);
boolean b=m.find();
if (b)
{
return true;
}
return false;
}
privatebooleansetCredits(intcre)
{
if(cre>=1 &&cre<6)
{
return true;
}
return false;
}
7) Develop a class called Date that includes three pieces of information as instance
variables—a month (type int), a day (type int) and a year (type int). The class should
have a parameterized constructor that initializes the three instance variables. Provide a
set and a get method for each instance variable. Set the data only when values are
positive. Provide a method toString() that displays the month, day and year separated
by forward slashes (/). Write a test application named DateTest that demonstrates class
Date’s capabilities.
class Date
{
int day;
int month;
int year;
Date(intd,intm,int y)
{
day=d;
month=m;
year=y;
}
booleansetdate(intday,intmonth,int year)
{
if(day>0&&month>0&&year>0)
{
this.day=day;
this.month=month;
this.year=year;
return true;
}
else
{
return false;
}
}
public intgetDay() {
return day;
}
public intgetMonth() {
return month;
}
2M
public intgetYear() {
return year;
}
public String toString()
{
String s=String.format("%d / %d /%d",getMonth(),getDay(),getYear()); -
>1M
return s;
}
}
8) Some websites impose certain rules for passwords. Suppose the password rules are as
follows: ¦ A password must have at least eight characters. ¦ A password consists of only
letters and digits. Write main () method that prompts the user to enter a password and
a static method isValidPassword() that expects a string argument and returns boolean
type after validating the password.
import java.util.Scanner;
class Password
{
String pass;
staticbooleanisValidPassword(String p)
{
if((p.length()>=8) &&p.matches(".*[a-zA-Z].*") &&p.matches(".*[0-9].*"))
{
return true;
}
else
{ return false; }
}
}
public class Passwordrule
{
public static void main(String[] args)
{
String pas;
Scanner s=new Scanner(System.in);
System.out.println("Enter the password");
pas=s.next();
boolean res=Password.isValidPassword(pas);
if(res==true)
{
System.out.println("password is valid");
}
else
{
System.out.println("password is invalid");
}
}
}
Part – C {2 x 9 Marks = 18 Marks}
9) The supervisor of a movie theatre decides to automate Ticket Booking. The task is to
develop a class Ticket with TicketID, number of seats, date and fare as instance data
members and a static fields totalSeatsBooked and totalTicketsBooked. Write getters
and setters. Draw the class diagram and a TicketDemo class to create object and access
Ticket class methods. (Input data to be read from console.)
package stringmethod;
import java.util.Scanner;
public class TicketDemo
{
public static void main(String[] args)
{
Ticket obj=new Ticket();
Scanner s=new Scanner(System.in);
System.out.println("Enter the TicketId:");
long a=s.nextLong();
obj.setId(a);
System.out.println("Enter the number of Seats:");
int b=s.nextInt();
obj.setSeats(b);
System.out.println("Enter the Fare:");
long d=s.nextLong();
obj.setFare(d);
System.out.println("Enter the Date:");
String c=s.next();
obj.setDate(c);
Ticket.totalTicketsBooked=1;
Ticket.totalSeatsBooked=obj.getSeats();
String cc=obj.getDate();
long dd=obj.getFare();
System.out.println("Total Tickets
Booked="+Ticket.totalTicketsBooked);
System.out.println("Total Seats
Booked="+Ticket.totalSeatsBooked);
System.out.println("Total Fare="+(obj.getSeats()*dd));
System.out.println("DATE="+cc);
s.close();
}
}
---------------------------------------------------
package Stringmethod;
public class Ticket
{
private long TicketID;
private int no_of_seat;
private String date;
private long fare;
static long totalSeatsBooked;
static long totalTicketsBooked;
void setId(long id)
{
TicketID=id;
}
void setSeats(int seat)
{
no_of_seat=seat;
}
void setDate(String dat)
{
date=dat;
}
void setFare(long rate) {
fare=rate;
}
long getId()
{
return TicketID;
}
int getSeats() {return no_of_seat;}
String getDate() {
return date; }
long getFare() { return fare;}
}
10) A cab booking app is to be launched. The task is to store data of Passengers in a
class
with attributes Name, Mobile, distance and fare. Write mutators for
a) name – has only characters
b) mobile – 10 digits
c) distance - must be a positive value (in terms of kms)
A method to compute fare at the rate of Rs.10 per km and toString() method to print
data. Modularize to package level with main () in PassengerDemo class to create an
object and obtain the data through console.
package p1;
publicclass Passanger {
private String name,mobile;
privateint distance;
publicboolean setName(String a)
{
int i;
for(i=0;i<a.length();i++)
{
if(a.charAt(i)>=65 &&a.charAt(i)<=90 || a.charAt(i)>=97 &&a.charAt(i)<=122)
continue;
else
returnfalse;
}
name=a;
returntrue;
}
publicboolean setMobile(String b)
{
if(b.length()==10)
{mobile=b;
returntrue;
}
else
returnfalse;
}
publicboolean setDistance(int a)
{
if(a>0)
{
distance = a;
returntrue;
}
returnfalse;
}
public String getName()
{
return name;
}
public String getMobile()
{
return mobile;
}
publicint getDistance()
{
return distance;
}
publicint getFare()
{
return distance *10;
}
public String toString()
{
return "name = "+getName()+"\n"+"mobile no = "+getMobile()+"\n"+"distance =
"+getDistance()+"\n"+"fare ="+getFare();
}
}
package p2;
import java.util.Scanner;
import p1.Passanger;
public class PassangerDemo {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Passanger p=new Passanger();
String a,b;
int c;
a=sc.next();
b=sc.next();
c=sc.nextInt();
if(p.setName(a)&&p.setMobile(b)&&p.setDistance(c))
System.out.println(p.toString());
else
System.out.println("wrong format");
sc.close();
}}
11) The Election Commission requires the following task to be done. A class Voter with
ID,
name, age and address as fields. Write toString() , getter methods and setData() method.
The VoterDemo has main () method which reads and stores data of 10 voters and
displays a menu with following operations:
a) Add new voter
b) Search voter based on ID
c) Search voter whose name starts with "A”
package p2;
publicclass Voter
{
privatelongid;
private String name,address;
privateintage;
publicvoidsetData(longid, String name,intage,Stringaddress)
{
this.id=id;
this.name=name;
this.age=age;
this.address=address;
}
public String toString()
{
return"Voter id = "+id+" Voter Name =" +name+" Voter age =" +age+"\n Address =
"+address;
}
publiclonggetId()
{
returnid;
}
publicStringgetName()
{
return name;
}
}
package p2;
importjava.util.Scanner;
publicclassVoterDemo
{
publicstaticintlinearSearch(Voter v[],intn,longkey)
{
for(inti=0;i<n;i++)
{
if(v[i].getId()==key)
returni;
}
return -1;
}
publicstaticvoidlinearSearch(Voter v[],intn)
{
intflag=0;
for(inti=0;i<n;i++) {
2M
if(v[i].getName().charAt(0) == 'A'){
flag=1;
System.out.println(v[i]);}
}
if(flag ==0)
System.out.println("no voter whose name starts with A");
}
publicstaticvoid main(String[] args)
{
Voter v[]=new Voter[10];
Scanner sc = new Scanner(System.in);
intchoice,nov=0,index;
while(true)
{
System.out.println("Menu");
System.out.println("1. Add new voter");
System.out.println("2. Search voter based on ID");
System.out.println("3. Search voter whose name starts with 'A'");
System.out.println("4. exit");
choice =sc.nextInt();
switch(choice)
{
case 1:
v[nov]=newVoter();
System.out.println("Enter id, name, age and address of voter");
longid=sc.nextLong();
sc.nextLine();
String name=sc.nextLine();
intage=sc.nextInt();
sc.nextLine();
String address=sc.nextLine();
v[nov].setData(id,name,age,address);
nov++;
break;
case 2:
System.out.println("enter the id of voter");
longkey=sc.nextLong();
index=linearSearch(v,nov,key);
if(index != -1)
{
System.out.println("voter details are");
System.out.println(v[index]);
}
else
System.out.println("Search id not found");
break;
case 3:
linearSearch(v,nov);
break;
case 4:
System.exit(0);
}
}
}
}
12) A vehicle registration portal accepts the following data from Vehicle owners:
a) Vehicle Number – 8 letters (can contain digits and characters)
b) Wheeler (either 2 or 4)
c) Owner name – can contain only characters
d) Mobile – 10 digits. Draw the class diagram and Vehicle class contains parameterized
constructor, toString() methods. The Vehicle Demo class has a main () method which
reads and stores data of 5 vehicles from a file and displays the menu with following
operations: a) Add data b) Display data based on vehicle number c) Print data of all
vehicles
package automobiles;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import java.io.File;
public class Vehicle {
private String vno;
private int wheeler;
private String owner;
private long mobile;
Vehicle() { }
Vehicle(String vno,int wheeler,String owner,long mobile)
{
this.vno=vno;
this.wheeler=wheeler;
this.owner=owner;
this.mobile=mobile;
}
public void writeRecord()throws Exception
{
FileWriter fw=new FileWriter("C:\\Users\\srira\\eclipseworkspace\\automobiles\\src
\\automobiles\\vehinfo",true);
PrintWriter pw=new PrintWriter(fw);
pw.write("\n"+vno+"\t"+wheeler+"\t"+owner+"\t"+mobile);
pw.close();
}
public void display(String vno)throws Exception
{
File f=new File("C:\\Users\\srira\\eclipse-workspace\\automobiles\\src\\automobiles\\
vehinfo");
Scanner s=new Scanner(f);
while(s.hasNextLine())
{
String no=s.next();
int w=s.nextInt();
String o=s.next();
long m=s.nextLong();
if(no.equals(vno))
{
System.out.println(this);
break;
}
}
}
public void display()throws Exception
{
File f=new File("C:\\Users\\srira\\eclipse-workspace\\automobiles\\src\\automobiles\\
vehinfo");
Scanner s=new Scanner(f);
while(s.hasNextLine())
{
String no=s.next();
int w=s.nextInt();
String o=s.next();
long m=s.nextLong();
System.out.println(this);
}
package automobiles;
import java.util.Scanner;
public class VehicleDemo {
int choice;
Scanner s=new Scanner(System.in);
Vehicle v[]=new Vehicle[5];
for(int i=0;i<2;i++)
{
System.out.println("Enter vehicle number:");
String no=s.next()+s.nextLine();
System.out.println("Enter vehicle type:");
int w=s.nextInt();
System.out.println("Enter vehicle owner:");
String o=s.next()+s.nextLine();
System.out.println("Enter mobile:");
long m=s.nextLong();
v[i]=new Vehicle(no,w,o,m);
v[i].writeRecord();
}
do
{
System.out.println("1.Add data\n2.Display Data based on vehicle number\n
3.Print the data of all vehicles\n");
choice=s.nextInt();
switch(choice)
{
case 1:
String no=s.next()+s.nextLine();
int w=s.nextInt();
String o=s.next()+s.nextLine();
long m=s.nextLong();
Vehicle vi=new Vehicle(no,w,o,m);
vi.writeRecord();
break;
case 2:
Vehicle ve=new Vehicle();
System.out.println("Enter vehicle number");
ve.display(s.nextLine());
break;
case 3:
for(int i=0;i<v.length;i++)
v[i].display();
break;
default:System.out.println("INVALIED");
}
}while(choice!=0);
s.close();
}
}
SEMESTER IN I EXAM
ANSWER KEY
1 : Define the terms class, object and explain about access specifiers.
Syntax:
member variable(s);
member method(s);
Syntax: 1M
The access specifier in Java specifies the accessibility or scope of a field, method,
constructor, or class. There are four types of Java access specifiers :
Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
Default: The access level of a default modifier is only within the package. It cannot
be accessed from outside the package. If you do not specify any access level, it will
be the default.
Protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it
cannot be accessed from outside the package.
2. Draw the class diagram for the following and Develop a java program that
reads the number of kilograms of type double, through console, converts it to
pounds, displays the result.(HINT: 1kg = 2.2046 pounds )
package pack8;
import java.util.Scanner;
{ this.kg=k;
System.out.println("After conversion: \n"+ this.kg +" kg =" +(this.kg*2.2046)+"
"+"pounds");
double n=sc.nextDouble();
kg.convertKgToPounds(n);
sc.close();
3.
{this.isbn=I;}
{this.title=t;}
{this.price=p;}
public longgetIsbn()
{return isbn;}
public StringgetTitle()
{return title;}
public doublegetPrice()
{return price;}
String s;
return s;
b.setIsbn(sc.nextLong());
b.setTitle(sc.next());
b.setPrice(sc.nextDouble());
system.out.println(b);
}
4.
public class First
{
public static void main(String[] args)
{
int sum=0,m1,m2,m3,m4,m5,m6,avg;
for(int i=0;i<args.length;i++)
{
sum=sum+Integer.parseInt(args[i]);
}
avg=sum/6;
System.out.println(avg);
m1=Integer.parseInt(args[0]);
m2=Integer.parseInt(args[1]);
m3=Integer.parseInt(args[2]);
m4=Integer.parseInt(args[3]);
m5=Integer.parseInt(args[4]);
m6=Integer.parseInt(args[5]);
if(m1>m2&&m1>m3&&m1>m4&&m1>m5)
{
System.out.println(m1);
}
else if(m2>m3&&m2>m4&&m2>m5)
System.out.println(m2);
else if(m3>m4&&m3>m5)
System.out.println(m3);
else if(m4>m5)
System.out.println(m4);
else
System.out.println(m5);
}}
5 a)
package question5;
if(d>0)
distance=d;
return true;
else
return false;
this.name=name;
{
this.mobile=mobile;
return name;
return mobile;
return distance;
fare=distance*10;
return fare;
String s=String.format("NAME=%s\nMOBILE=%d\nDISTANCE=%d\nFARE=
%d",getName(),getMobile(),getDistance(),computeFare());
return s;
}
package temp;
import java.util.Scanner;
import question5.Passengers;
String name=sc.next();
long mobile=sc.nextLong();
int distance=sc.nextInt();
r.setName(name);
r.setMobile(mobile);
r.setDistance(distance);
System.out.println(r.toString());
sc.close();
}
6. package question6;
return courseCode;
if(courseCode.length()<=6&&courseCode.matches("^(?=.*[A-Z])(?=.*[0-9])[A-
Z0-9]+$"))
{
return true;
else
return false;
return courseTitle;
@Override
this.courseTitle = courseTitle;
return credits;
this.credits = credits;
return true;
else
System.out.println("Invalied Credits");
return false;
import java.util.*;
String cc;
String ct;
int cr;
cc=scan.nextLine();
if(!c.setCourseCode(cc))
{
ct=scan.nextLine();
c.setCourseTitle(ct);
cr=Integer.parseInt(scan.nextLine());
if(!c.setCredits(cr))
System.out.println("Inavalied Credits");
System.out.println(c);
scan.close();
INPUT/OUTPUT:
20SC1101
20S11
Enter credits
Invalied Credits
Inavalied Credits
20SC11
OOP
Enter credits
Class TwoDimensionalPoint {
double x, y;
This.x=x;
This.y =y;
}
8.
Class Loan
Double annualROI;
Loan ()
loanAmount=0;
numberOfYears=0;
annualROI=0;
This ();
loanAmount=la;
numberOfYears=noi;
}
9. Draw the class Diagram and code the class Triangle with base and height as
private attributes of type double. Define a no argument constructor and overload it
with parameterized constructor. Also write a method area() that computes the area
of a triangle and returns the result and code the toString() method.
Solution:
import java.util.Scanner;
public Triangle(){ 1M
base = 2;
height = 4;
this.base = base;
this.height = height;
return 0.5*base*height;
String s;
s="Base:"+base+"\nHeight:"+height+"\nArea:"+area();
return s;
}
public static void main(String[] args) { 2M
System.out.println(ob);
double b = sc.nextDouble();
double h = sc.nextDouble();
System.out.println(ob1);
sc.close();
Class Diagram:
10. Let S1 be “Welcome” and s2 be “welcome” .Write the code for the following
statements and justify the answer.
Solution:
String s1 = "Welcome";
String s2 = "welcome";
System.out.println (b);
b=s1.endsWith ("AAA");
System.out.println (b);
String s3 = s1+s2;
System.out.println (s3);
System.out.println (s4);
}}
11
package mypack1;
publicclass LinearEquation {
privateinta,b,c,d,e,f,x,y;
publicLinearEquation(inta,intb,intc,intd,inte,intf)
{
this.a=a;
this.b=b;
this.c=c;
this.d=d;
this.e=e;
this.f=f;
}
publicboolean isSolvable()
{
intresult;
result=(this.a*this.d)-(this.b*this.c);
if(result==0)
returnfalse;
else
returntrue;
}
publicint getX()
{
this.x=(e*d-b*f)/(a*d-b*c);
returnthis.x;
}
publicint getY()
{
this.y=(a*f-e*c)/(a*d-b*c);
returnthis.y;
}
}
package mypack2;
import mypack1.LinearEquation;
import java.util.Scanner;
publicclass LinearDemo {
publicstaticvoid main(String args[])
{
Scanner sc=new Scanner(System.in);
inta,b,c,d,e,f;
System.out.println("enter a,b,c,d,e,f");
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
d=sc.nextInt();
e=sc.nextInt();
f=sc.nextInt();
LinearEquation le=new
LinearEquation(a,b,c,d,e,f);
if(le.isSolvable())
{
System.out.println("x="+le.getX()
+"y="+le.getY());
}
else
System.out.println("the equation has no
solution");
12. Modularize the design to package level and develop the code. A Vehicle registration
portal accepts the following data from Vehicle owners: a) Vehicle Number
b)Wheeler(either 2or4)-validate in setter c) Owner name d) Mobile. The Vehicle class
contains parameterised constructor, toString() methods. The vehicledemo class has a
main() method which reads and stores data of 5 vehicles and displays the menu with
following operations: a) Add data 2) Display data based on vehicle number.
(12.5Marks)
In vehicle class:
package First;
public class Vehicle
{
private String Vno;
private int wel;
private String own;
private long pno;
In VehicleDemo class:
package First;
import java.util.Scanner;