0% found this document useful (0 votes)
76 views41 pages

11

The document discusses defining multiple classes with data members and member methods to perform various tasks like calculating sums, checking if numbers are pythagorean triplets, calculating taxes, discounts and telephone bills based on given conditions. Main focus is on defining classes with appropriate data members and methods.

Uploaded by

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

11

The document discusses defining multiple classes with data members and member methods to perform various tasks like calculating sums, checking if numbers are pythagorean triplets, calculating taxes, discounts and telephone bills based on given conditions. Main focus is on defining classes with appropriate data members and methods.

Uploaded by

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

1. Define a class Calculate to accept two numbers as instance variables.

Use
the following member methods for the given purposes:
Class name — Calculate

Data members — int a, int b

Member methods:
void inputdata() — to input both the values
void calculate() — to find sum and difference
void outputdata() — to print sum and difference of both the numbers
Use a main method to call the functions.

Ans:

import java.util.*;
public class Calculate
{
int a, b;
public void inputdata()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter first number: ");
a = sc.nextInt();
System.out.print("Enter second number: ");
b = sc.nextInt();
}
int sum, diff;
public void calculate()
{
sum = a + b;
diff = a - b;
}
public void outputdata()
{
System.out.println("Sum = " + sum);
System.out.println("Difference = " + diff);
}
public static void main(String args[])
{
Calculate obj = new Calculate();
obj.inputdata();
obj.calculate();
obj.outputdata();
}
}

2. Define a class Triplet with the following specifications:

Class name — Triplet

Data Members — int a, int b, int c

Member Methods:
void getdata() — to accept three numbers
void findprint() — to check and display whether the numbers are Pythagorean Triplets or not.

import java.util.Scanner;

public class Triplet


{
private int a;
private int b;
private int c;

public void getdata() {


Scanner in = new Scanner(System.in);
System.out.print("Enter a: ");
a = in.nextInt();
System.out.print("Enter b: ");
b = in.nextInt();
System.out.print("Enter c: ");
c = in.nextInt();
}

public void findprint() {


if ((Math.pow(a, 2) + Math.pow(b, 2)) == Math.pow(c, 2)
|| (Math.pow(b, 2) + Math.pow(c, 2)) == Math.pow(a, 2)
|| (Math.pow(a, 2) + Math.pow(c, 2)) == Math.pow(b, 2))
System.out.print("Numbers are Pythagorean Triplets");
else
System.out.print("Numbers are not Pythagorean Triplets");
}

public static void main(String args[]) {


Triplet obj = new Triplet();
obj.getdata();
obj.findprint();
}
}

Define a class Employee having the following description:

Class name : Employee

Data Members Purpose

int pan To store personal account number

String name To store name

double taxincome To store annual taxable income

double tax To store tax that is calculated

Member functions Purpose

void input() Store the pan number, name, taxable income

void cal() Calculate tax on taxable income

void display() Output details of an employee

Calculate tax based on the given conditions and display the output as

per the given format.

Total Annual Taxable Income Tax Rate

Up to ₹2,50,000 No tax
Total Annual Taxable Income Tax Rate

From ₹2,50,001 to ₹5,00,000 10% of the income exceeding ₹2,50,000

From ₹5,00,001 to ₹10,00,000 ₹30,000 + 20% of the income exceeding ₹5,00,000

Above ₹10,00,000 ₹50,000 + 30% of the income exceeding ₹10,00,000

import java.util.Scanner;

public class Employee


{
private int pan;
private String name;
private double taxincome;
private double tax;

public void input() {


Scanner in = new Scanner(System.in);
System.out.print("Enter pan number: ");
pan = in.nextInt();
in.nextLine();
System.out.print("Enter Name: ");
name = in.nextLine();
System.out.print("Enter taxable income: ");
taxincome = in.nextDouble();
}

public void cal() {


if (taxincome <= 250000)
tax = 0;
else if (taxincome <= 500000)
tax = (taxincome - 250000) * 0.1;
else if (taxincome <= 1000000)
tax = 30000 + ((taxincome - 500000) * 0.2);
else
tax = 50000 + ((taxincome - 1000000) * 0.3);
}

public void display() {


System.out.println("Pan Number\tName\tTax-Income\tTax");
System.out.println(pan + "\t" + name + "\t"
+ taxincome + "\t" + tax);
}

public static void main(String args[]) {


Employee obj = new Employee();
obj.input();
obj.cal();
obj.display();
}
}

Define a class Discount having the following description:

Class name : Discount

Data Members Purpose

int cost to store the price of an article

String name to store the customer's name

double dc to store the discount

double amt to store the amount to be paid

Member methods Purpose

void input() Stores the cost of the article and name of the customer

void cal() Calculates the discount and amount to be paid

void display() Displays the name of the customer, cost, discount and amount to be paid

Write a program to compute the discount according to the given conditions and display the output as
per the given format.

List Price Rate of discount

Up to ₹5,000 No discount

From ₹5,001 to ₹10,000 10% on the list price


List Price Rate of discount

From ₹10,001 to ₹15,000 15% on the list price

Above ₹15,000 20% on the list price

Output:

Name of the customer Discount Amount to be paid


.................... ........ .................
.................... ........ .................

import java.util.Scanner;

public class Discount


{
private int cost;
private String name;
private double dc;
private double amt;

public void input() {


Scanner in = new Scanner(System.in);
System.out.print("Enter customer name: ");
name = in.nextLine();
System.out.print("Enter article cost: ");
cost = in.nextInt();
}

public void cal() {


if (cost <= 5000)
dc = 0;
else if (cost <= 10000)
dc = cost * 0.1;
else if (cost <= 15000)
dc = cost * 0.15;
else
dc = cost * 0.2;

amt = cost - dc;


}

public void display() {


System.out.println("Name of the customer\tDiscount\tAmount to be paid");
System.out.println(name + "\t" + dc + "\t" + amt);
}
public static void main(String args[]) {
Discount obj = new Discount();
obj.input();
obj.cal();
obj.display();
}
}

Output

Question 5

Define a class Telephone having the following description:

Class name : Telephone

Data Members Purpose

int prv, pre to store the previous and present meter readings

int call to store the calls made (i.e. pre - prv)

String name to store name of the consumer

double amt to store the amount

double total to store the total amount to be paid

Member functions Purpose

void input() Stores the previous reading, present reading and name of the consumer

void cal() Calculates the amount and total amount to be paid

void display() Displays the name of the consumer, calls made, amount and total amount to be paid
Write a program to compute the monthly bill to be paid according to the given conditions and display
the output as per the given format.

Calls made Rate

Up to 100 calls No charge

For the next 100 calls 90 paise per call

For the next 200 calls 80 paise per call

More than 400 calls 70 paise per call

However, every consumer has to pay ₹180 per month as monthly rent for availing the service.

Output:

Name of the customer Calls made Amount to be paid


.................... .......... .................
.................... .......... .................

import java.util.Scanner;

public class Telephone


{
private int prv;
private int pre;
private int call;
private String name;
private double amt;
private double total;

public void input() {


Scanner in = new Scanner(System.in);
System.out.print("Enter Customer Name: ");
name = in.nextLine();
System.out.print("Enter previous reading: ");
prv = in.nextInt();
System.out.print("Enter present reading: ");
pre = in.nextInt();
}

public void cal() {


call = pre - prv;
if (call <= 100)
amt = 0;
else if (call <= 200)
amt = (call - 100) * 0.9;
else if (call <= 400)
amt = (100 * 0.9) + (call - 200) * 0.8;
else
amt = (100 * 0.9) + (200 * 0.8) + ((call - 400) * 0.7);

total = amt + 180;


}

public void display() {


System.out.println("Name of the customer\tCalls made\tAmount to be paid");
System.out.println(name + "\t" + call + "\t" + total);
}

public static void main(String args[]) {


Telephone obj = new Telephone();
obj.input();
obj.cal();
obj.display();
}
}

Output

Question 6

Define a class Interest having the following description:

Class name : Interest

Data Members Purpose

int p to store principal (sum)

int r to store rate

int t to store time

double interest to store the interest to be paid


Data Members Purpose

double amt to store the amount to be paid

Member functions Purpose

void input() Stores the principal, rate, time

void cal() Calculates the interest and amount to be paid

void display() Displays the principal, interest and amount to be paid

Write a program to compute the interest according to the given conditions and display the output.

Time Rate of interest

For 1 year 6.5%

For 2 years 7.5%

For 3 years 8.5%

For 4 years or more 9.5%

(Note: Time to be taken only in whole years)

import java.util.Scanner;

public class Interest


{
private int p;
private float r;
private int t;
private double interest;
private double amt;

public void input() {


Scanner in = new Scanner(System.in);
System.out.print("Enter principal: ");
p = in.nextInt();
System.out.print("Enter time: ");
t = in.nextInt();
}

public void cal() {


if (t == 1)
r = 6.5f;
else if (t == 2)
r = 7.5f;
else if (t == 3)
r = 8.5f;
else
r = 9.5f;

interest = (p * r * t) / 100.0;
amt = p + interest;
}

public void display() {


System.out.println("Principal: " + p);
System.out.println("Interest: " + interest);
System.out.println("Amount Payable: " + amt);
}

public static void main(String args[]) {


Interest obj = new Interest();
obj.input();
obj.cal();
obj.display();
}
}

Output

Question 7

Define a class Library having the following description:

Class name : Library

Data Members Purpose

String name to store name of the book


Data Members Purpose

int price to store the printed price of the book

int day to store the number of days for which fine is to be paid

double fine to store the fine to be paid

Member functions Purpose

void input() To accept the name of the book and printed price of the book

void cal() Calculates the fine to be paid

void display() Displays the name of the book and fine to be paid

Write a program to compute the fine according to the given conditions and display the fine to be paid.

Days Fine

First seven days 25 paise per day

Eight to fifteen days 40 paise per day

Sixteen to thirty days 60 paise per day

More than thirty days 80 paise per day

import java.util.Scanner;

public class Library


{
private String name;
private int price;
private int day;
private double fine;

public void input() {


Scanner in = new Scanner(System.in);
System.out.print("Enter name of the book: ");
name = in.nextLine();
System.out.print("Enter printed price of the book: ");
price = in.nextInt();
System.out.print("For how many days fine needs to be paid: ");
day = in.nextInt();
}

public void cal() {


if (day <= 7)
fine = day * 0.25;
else if (day <= 15)
fine = (7 * 0.25) + ((day - 7) * 0.4);
else if (day <= 30)
fine = (7 * 0.25) + (8 * 0.4) + ((day - 15) * 0.6);
else
fine = (7 * 0.25) + (8 * 0.4) + (15 * 0.6) + ((day - 30) * 0.8);
}

public void display() {


System.out.println("Name of the book: " + name);
System.out.println("Fine to be paid: " + fine);
}

public static void main(String args[]) {


Library obj = new Library();
obj.input();
obj.cal();
obj.display();
}
}

Output

Question 8

Bank charges interest for the vehicle loan as given below:

Number of years Rate of interest

Up to 5 years 15%

More than 5 and up to 10 years 12%


Number of years Rate of interest

Above 10 years 10%

Write a program to model a class with the specifications given below:

Class name: Loan

Data Members Purpose

int time Time for which loan is sanctioned

double principal Amount sanctioned

double rate Rate of interest

double interest To store the interest

double amt Amount to pay after given time

Member Methods Purpose

void getdata() To accept principal and time

To find interest and amount.


void calculate() Interest = (Principal*Rate*Time)/100
Amount = Principal + Interest

void display() To display interest and amount

import java.util.Scanner;

public class Loan


{
private int time;
private double principal;
private double rate;
private double interest;
private double amt;
public void getdata() {
Scanner in = new Scanner(System.in);
System.out.print("Enter principal: ");
principal = in.nextInt();
System.out.print("Enter time: ");
time = in.nextInt();
}

public void calculate() {


if (time <= 5)
rate = 15.0;
else if (time <= 10)
rate = 12.0;
else
rate = 10.0;

interest = (principal * rate * time) / 100.0;


amt = principal + interest;
}

public void display() {


System.out.println("Interest = " + interest);
System.out.println("Amount Payable = " + amt);
}

public static void main(String args[]) {


Loan obj = new Loan();
obj.getdata();
obj.calculate();
obj.display();
}
}

Output

Question 9

Hero Honda has increased the cost of its vehicles as per the type of the engine using the following
criteria:

Type of Engine Rate of increment

2 stroke 10% of the cost


Type of Engine Rate of increment

4 stroke 12% of the cost

Write a program by using a class to find the new cost as per the given specifications:

Class name: Honda

Data Members Purpose

int type To accept type of engine 2 stroke or 4 stroke

int cost To accept previous cost

Member Methods Purpose

void gettype() To accept the type of engine and previous cost

void find() To find the new cost as per the criteria given above

void printcost() To print the type and new cost of the vehicle

import java.util.Scanner;

public class Honda


{
private int type;
private int cost;
private double newCost;

public void gettype() {


Scanner in = new Scanner(System.in);
System.out.print("Enter type: ");
type = in.nextInt();
System.out.print("Enter cost: ");
cost = in.nextInt();
}

public void find() {


switch (type) {
case 2:
newCost = cost + (cost * 0.1);
break;

case 4:
newCost = cost + (cost * 0.12);
break;

default:
System.out.println("Incorrect type");
break;
}
}

public void printcost() {


System.out.println("Type: " + type);
System.out.println("New cost: " + newCost);
}

public static void main(String args[]) {


Honda obj = new Honda();
obj.gettype();
obj.find();
obj.printcost();
}
}

Output

Question 10

Define a class called 'Mobike' with the following specifications:

Data Members Purpose

int bno To store the bike number

int phno To store the phone number of the customer

String name To store the name of the customer


Data Members Purpose

int days To store the number of days the bike is taken on rent

int charge To calculate and store the rental charge

Member Methods Purpose

void input() To input and store the details of the customer

void compute() To compute the rental charge

void display() To display the details in the given format

The rent for a mobike is charged on the following basis:

Days Charge

For first five days ₹500 per day

For next five days ₹400 per day

Rest of the days ₹200 per day

Output:

Bike No. Phone No. Name No. of days Charge


xxxxxxx xxxxxxxx xxxx xxx xxxxxx

import java.util.Scanner;

public class Mobike


{
private int bno;
private int phno;
private int days;
private int charge;
private String name;

public void input() {


Scanner in = new Scanner(System.in);
System.out.print("Enter Customer Name: ");
name = in.nextLine();
System.out.print("Enter Customer Phone Number: ");
phno = in.nextInt();
System.out.print("Enter Bike Number: ");
bno = in.nextInt();
System.out.print("Enter Number of Days: ");
days = in.nextInt();
}

public void compute() {


if (days <= 5)
charge = days * 500;
else if (days <= 10)
charge = (5 * 500) + ((days - 5) * 400);
else
charge = (5 * 500) + (5 * 400) + ((days - 10) * 200);
}

public void display() {


System.out.println("Bike No.\tPhone No.\tName\tNo. of days \tCharge");
System.out.println(bno + "\t" + phno + "\t" + name + "\t" + days
+ "\t" + charge);
}

public static void main(String args[]) {


Mobike obj = new Mobike();
obj.input();
obj.compute();
obj.display();
}
}

Output

Question 11

Write a program using a class with the following specifications:

Class name: Caseconvert


Data Members Purpose

String str To store the string

Member Methods Purpose

void getstr() to accept a string

void convert() to obtain a string after converting each upper case letter into lower case and vice versa

void display() to print the converted string

import java.util.Scanner;

public class Caseconvert


{
private String str;
private String convStr;

public void getstr() {


Scanner in = new Scanner(System.in);
System.out.print("Enter the string: ");
str = in.nextLine();
}

public void convert() {


char arr[] = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
if (Character.isUpperCase(str.charAt(i)))
arr[i] = Character.toLowerCase(str.charAt(i));
else if (Character.isLowerCase(str.charAt(i)))
arr[i] = Character.toUpperCase(str.charAt(i));
else
arr[i] = str.charAt(i);
}
convStr = new String(arr);
}

public void display() {


System.out.println("Converted String:");
System.out.println(convStr);
}

public static void main(String args[]) {


Caseconvert obj = new Caseconvert();
obj.getstr();
obj.convert();
obj.display();
}
}

Output

Question 12

Write a program by using a class with the following specifications:

Class name: Vowel

Data Members Purpose

String s To store the string

int c To count vowels

Member Methods Purpose

void getstr() to accept a string

void getvowel() to count the number of vowels

void display() to print the number of vowels

import java.util.Scanner;

public class Vowel


{
private String s;
private int c;

public void getstr() {


Scanner in = new Scanner(System.in);
System.out.print("Enter the string: ");
s = in.nextLine();
}

public void getvowel() {


String temp = s.toUpperCase();
c = 0;
for (int i = 0; i < temp.length(); i++) {
char ch = temp.charAt(i);
if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O'
|| ch == 'U')
c++;
}
}

public void display() {


System.out.println("No. of Vowels = " + c);
}

public static void main(String args[]) {


Vowel obj = new Vowel();
obj.getstr();
obj.getvowel();
obj.display();
}
}

Output

Question 13

A bookseller maintains record of books belonging to the various publishers. He uses a class with the
specifications given below:

Class name — Stock

Data Members:

1. String title — Contains title of the book


2. String author — Contains author name
3. String pub — Contains publisher's name
4. int noc — Number of copies

Member Methods:

1. void getdata() — To accept title, author, publisher's name and the number of copies.
2. void purchase(int t, String a, String p, int n) — To check the existence of the book in the stock
by comparing total, author's and publisher's name. Also check whether noc >n or not. If yes,
maintain the balance as noc-n, otherwise display book is not available or stock is under
flowing.

Write a program to perform the task given above.

import java.util.Scanner;

public class Stock


{
private String title;
private String author;
private String pub;
private int noc;

public void getdata() {


Scanner in = new Scanner(System.in);
System.out.print("Enter book title: ");
title = in.nextLine();
System.out.print("Enter book author: ");
author = in.nextLine();
System.out.print("Enter book publisher: ");
pub = in.nextLine();
System.out.print("Enter no. of copies: ");
noc = in.nextInt();
}

public void purchase(String t, String a, String p, int n) {


if (title.equalsIgnoreCase(t) &&
author.equalsIgnoreCase(a) &&
pub.equalsIgnoreCase(p)) {
if (noc > n) {
noc -= n;
System.out.println("Updated noc = " + noc);
}
else {
System.out.println("Stock is under flowing");
}
}
else {
System.out.println("Book is not available");
}
}

public static void main(String args[]) {


Stock obj = new Stock();
obj.getdata();
obj.purchase("wings of fire", "APJ Abdul Kalam",
"universities press", 10);
obj.purchase("Ignited Minds", "APJ Abdul Kalam",
"Penguin", 5);
obj.purchase("wings of fire", "APJ Abdul Kalam",
"universities press", 20);
}
}

Output

Question 14

Write a program by using class with the following specifications:

Class name — Characters

Data Members:

1. String str — To store the string

Member Methods:

1. void input (String st) — to assign st to str


2. void check_print() — to check and print the following:
(i) number of letters
(ii) number of digits
(iii) number of uppercase characters
(iv) number of lowercase characters
(v) number of special characters

import java.util.Scanner;

public class Characters


{
private String str;

public void input(String st) {


str = st;
}

public void check_print() {


int cLetters = 0, cDigits = 0, cUpper = 0, cLower = 0,
cSpecial = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch >= 'A' && ch <= 'Z') {
cLetters++;
cUpper++;
}
else if (ch >= 'a' && ch <= 'z') {
cLetters++;
cLower++;
}
else if (ch >= '0' && ch <= '9') {
cDigits++;
}
else if (!Character.isWhitespace(ch)) {
cSpecial++;
}
}

System.out.println("Number of Letters: " + cLetters);


System.out.println("Number of Digits: " + cDigits);
System.out.println("Number of Upppercase Characters: "
+ cUpper);
System.out.println("Number of Lowercase Characters: "
+ cLower);
System.out.println("Number of Special Characters: "
+ cSpecial);
}

public static void main(String args[]) {


Scanner in = new Scanner(System.in);
System.out.print("Enter the string: ");
String s = in.nextLine();
Characters obj = new Characters();
obj.input(s);
obj.check_print();
}
}

Output

Question 15

Define a class Student with the following specifications:


Class Name : Student

Data Members Purpose

String name To store the name of the student

int eng To store marks in English

int hn To store marks in Hindi

int mts To store marks in Maths

double total To store total marks

double avg To store average marks

Member Methods Purpose

void accept() To input marks in English, Hindi and Maths

void compute() To calculate total marks and average of 3 subjects

void display() To show all the details viz. name, marks, total and average

Write a program to create an object and invoke the above methods.

import java.util.Scanner;

public class Student


{
private String name;
private int eng;
private int hn;
private int mts;
private double total;
private double avg;

public void accept() {


Scanner in = new Scanner(System.in);
System.out.print("Enter student name: ");
name = in.nextLine();
System.out.print("Enter marks in English: ");
eng = in.nextInt();
System.out.print("Enter marks in Hindi: ");
hn = in.nextInt();
System.out.print("Enter marks in Maths: ");
mts = in.nextInt();
}

public void compute() {


total = eng + hn + mts;
avg = total / 3.0;
}

public void display() {


System.out.println("Name: " + name);
System.out.println("Marks in English: " + eng);
System.out.println("Marks in Hindi: " + hn);
System.out.println("Marks in Maths: " + mts);
System.out.println("Total Marks: " + total);
System.out.println("Average Marks: " + avg);
}

public static void main(String args[]) {


Student obj = new Student();
obj.accept();
obj.compute();
obj.display();
}
}

Output

Question 16

Define a class called ParkingLot with the following description:

Class name : ParkingLot

Data Members Purpose

int vno To store the vehicle number

int hours To store the number of hours the vehicle is parked in the parking lot
Data Members Purpose

double bill To store the bill amount

Member
Purpose
Methods

void input( ) To input the vno and hours

void To compute the parking charge at the rate ₹3 for the first hour or the part thereof and ₹1.50
calculate( ) for each additional hour or part thereof.

void display() To display the detail

Write a main method to create an object of the class and call the above methods.

import java.util.Scanner;

public class ParkingLot


{
private int vno;
private int hours;
private double bill;

public void input() {


Scanner in = new Scanner(System.in);
System.out.print("Enter vehicle number: ");
vno = in.nextInt();
System.out.print("Enter hours: ");
hours = in.nextInt();
}

public void calculate() {


if (hours <= 1)
bill = 3;
else
bill = 3 + (hours - 1) * 1.5;
}

public void display() {


System.out.println("Vehicle number: " + vno);
System.out.println("Hours: " + hours);
System.out.println("Bill: " + bill);
}

public static void main(String args[]) {


ParkingLot obj = new ParkingLot();
obj.input();
obj.calculate();
obj.display();
}
}

Output

Question 17

Design a class RailwayTicket with following description:

Class name : RailwayTicket

Data Members Purpose

String name To store the name of the customer

String coach To store the type of coach customer wants to travel

long mob no To store customer's mobile number

int amt To store basic amount of ticket

int totalamt To store the amount to be paid after updating the original amount

Member
Purpose
Methods

void accept() To take input for name, coach, mobile number and amount

void update() To update the amount as per the coach selected (extra amount to be added in the amount as
Member
Purpose
Methods

per the table below)

void display() To display all details of a customer such as name, coach, total amount and mobile number

Type of Coaches Amount

First_AC ₹700

Second_AC ₹500

Third_AC ₹250

Sleeper None

Write a main method to create an object of the class and call the above member methods.

import java.util.Scanner;

public class RailwayTicket


{
private String name;
private String coach;
private long mobno;
private int amt;
private int totalamt;

private void accept() {


Scanner in = new Scanner(System.in);
System.out.print("Enter name: ");
name = in.nextLine();
System.out.print("Enter coach: ");
coach = in.nextLine();
System.out.print("Enter mobile no: ");
mobno = in.nextLong();
System.out.print("Enter amount: ");
amt = in.nextInt();
}

private void update() {


if(coach.equalsIgnoreCase("First_AC"))
totalamt = amt + 700;
else if(coach.equalsIgnoreCase("Second_AC"))
totalamt = amt + 500;
else if(coach.equalsIgnoreCase("Third_AC"))
totalamt = amt + 250;
else if(coach.equalsIgnoreCase("Sleeper"))
totalamt = amt;
}

private void display() {


System.out.println("Name: " + name);
System.out.println("Coach: " + coach);
System.out.println("Total Amount: " + totalamt);
System.out.println("Mobile number: " + mobno);
}

public static void main(String args[]) {


RailwayTicket obj = new RailwayTicket();
obj.accept();
obj.update();
obj.display();
}
}

Program 1- Define a class called Library with the following description:


Instance variables/data members:
Int acc_num – stores the accession number of the book
String title – stores the title of the book stores the name of the author
Member Methods:
(i) void input() – To input and store the accession number, title and author.
(ii)void compute – To accept the number of days late, calculate and display and fine charged at the rate of Rs.2
per day.
(iii) void display() To display the details in the following format:
Accession Number Title Author
Write a main method to create an object of the class and call the above member methods.
Solution -

public class Library {

int acc_num;
String title;
String author;
public void input() throws IOException {
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter accession number: ");
acc_num = Integer.parseInt(br.readLine());
System.out.print("Enter title: ");
title = br.readLine();
System.out.print("Enter author: ");
author = br.readLine();
}

public void compute() throws IOException {


BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter number of days late: ");
int daysLate = Integer.parseInt(br.readLine());;
int fine = 2 * daysLate;
System.out.println("Fine is Rs " + fine);
}

public void display() {


System.out.println("Accession Number\tTitle\tAuthor");
System.out.println(acc_num + "\t" + title + "\t" + author);
}

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


Library library = new Library();
library.input();
library.compute();
library.display();
}
}

Program 2- Given below is a hypothetical table showing rates of Income Tax for male citizens below the age
of 65 years:
Taxable Income (TI) in Income Tax in

Does not exceed 1,60,000 Nil

Is greater than 1,60,000 and less than or equal to 5,00,000 ( TI – 1,60,000 ) * 10%

Is greater than 5,00,000 and less than or equal to 8,00,000 [ (TI - 5,00,000 ) *20% ] + 34,000

Is greater than 8,00,000 [ (TI - 8,00,000 ) *30% ] + 94,000

Write a program to input the age, gender (male or female) and Taxable Income of a person.If the age is more
than 65 years or the gender is female, display “wrong category*.
If the age is less than or equal to 65 years and the gender is male, compute and display the Income Tax payable
as per the table given above.

Solution.
import java.util.Scanner;

public class IncomeTax {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter age: ");
int age = scanner.nextInt();
System.out.print("Enter gender: ");
String gender = scanner.next();
System.out.print("Enter taxable income: ");
int income = scanner.nextInt();
if (age > 65 || gender.equals("female")) {
System.out.println("Wrong category");
} else {
double tax;
if (income <= 160000) { tax =
0; } else if (income > 160000 && income <= 500000)
{ tax = (income - 160000) * 10 / 100; }
else if (income >= 500000 && income <= 800000) {
tax = (income - 500000) * 20 / 100 + 34000;
} else {
tax = (income - 800000) * 30 / 100 + 94000;
}
System.out.println("Income tax is " + tax);
}
}
}

Program 3- Write a program to accept a string. Convert the string to uppercase. Count and output the number
of double letter sequences that exist in the string.
Sample Input: “SHE WAS FEEDING THE LITTLE RABBIT WITH AN APPLE
Sample Output: 4

Solution.
import java.util.Scanner;

public class StringOperations {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter a String: ");
String input = scanner.nextLine();
input = input.toUpperCase();
int count = 0;
for (int i = 1; i < input.length(); i++) {
if (input.charAt(i) == input.charAt(i - 1)) {
count++;
}
}
System.out.println(count);
}

Program4- W Design a class to overload a function polygon() as follows:


(i) void polygon(int n, char ch) : with one integer argument and one character
type argument that draws a filled square of side n using the character stored
in ch.
(ii) void polygon(int x, int y) : with two integer arguments that draws a
filled rectangle of length x and breadth y, using the symbol ‘@’
(iii)void polygon( ) : with no argument that draws a filled triangle shown
below.

Example:
(i) Input value of n=2, ch=’O’
Output:
OO
OO
(ii) Input value of x=2, y=5
Output:
@@@@@
@@@@@
(iii) Output:
*
**
***

Solution.

public class Overloading {

public void polygon(int n, char ch) {

for (int i = 1; i <= n; i++) {

for (int j = 1; j <= n; j++) {

System.out.print(ch);

}
System.out.println();

public void polygon(int x, int y) {

for (int i = 1; i <= x; i++) {

for (int j = 1; j <= y; j++) {

System.out.print("@");

System.out.println();

public void polygon() {

for (int i = 1; i <= 3; i++) {

for (int j = 1; j <= i; j++) {

System.out.print("*");

System.out.println();
}

Program 5- Using the switch statement, writw a menu driven program to:
(i) Generate and display the first 10 terms of the Fibonacci
series 0,1,1,2,3,5….The first two Fibonacci numbers are 0 and 1, and each
subsequent number is the sum of the previous two.
(ii)Find the sum of the digits of an integer that is input.
Sample Input: 15390
Sample Output: Sum of the digits=18
For an incorrect choice, an appropriate error message should be displayed

Solution.

import java.util.Scanner;

public class Menu {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("Menu");

System.out.println("1. Fibonacci Sequence");


System.out.println("2. Sum of Digits");

System.out.print("Enter choice: ");

int choice = scanner.nextInt();

switch (choice) {

case 1:

int a = 0;

int b = 1;

System.out.print("0 1 ");

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


int c = a + b; System.out.print(c + "
"); a = b; b =
c; } break; case
2: System.out.print("Enter a number:
"); int num = scanner.nextInt();
int sum = 0; while (num > 0) {

int rem = num % 10;

sum = sum + rem;

num = num / 10;

System.out.println("Sum of digits is " + sum);

break;

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

Program6- Write a program to accept the names of 10 cities in a single dimension string array and their STD
(Subscribers Trunk Dialing) codes in another single dimension integer array. Search for a name of
a city input by the user in the list. If found, display “Search Successful” and print the name of the city along
with its STD code, or else display the message “Search Unsuccessful, No such city in the list’.

Solution.

import java.util.Scanner;

import java.util.Scanner;

public class Cities {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);


String[] cities = new String[10];

int[] std = new int[10];

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

System.out.print("Enter city: ");

cities[i] = scanner.next();

System.out.print("Enter std code: ");

std[i] = scanner.nextInt();

System.out.print("Enter city name to search: ");

String target = scanner.next();

boolean searchSuccessful = false;

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

if (cities[i].equals(target)) {

System.out.println("Search successful");

System.out.println("City : " + cities[i]);

System.out.println("STD code : " + std[i]);

searchSuccessful = true;

break;

}
}

if (!searchSuccessful) {

System.out.println("Search Unsuccessful, No such city


in the list");

You might also like