Download aspire java assignment!

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

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

Document related concepts
no text concepts found
Transcript
NTRODUCTION TO BASICS OF JAVA PROGRAMMING
ASSIGNMENT I
1. Write a program to find the difference between sum of the squares and the square of the sums of n
numbers
/*SUM OF SQUARES-SQUARE OF SUM OF N NUMBERS*/
import java.util.*;
class ssmss
{
public static void main(String[] args)
{
int sum=0,sum1=0,sum2=0;
Scanner input=new Scanner(System.in);
System.out.println("Enter value of n: ");
int n=input.nextInt();
for(int i=1;i<=n;i++)
{
int sq=i*i;
sum1+=sq;
}
System.out.println(sum1);
for(int i=1;i<=n;i++)
{
sum+=i;
}
sum2=sum*sum;
System.out.println(sum2);
int diff=0;
if(sum1>sum2)
{
diff=sum1-sum2;
}
else
{
diff=sum2-sum1;
}
System.out.println(diff);
}
}
2.Develop a program that accepts the area of a square and will calculate its perimeter.
/*PERIMETER FROM AREA*/
import java.util.*;
import java.text.*;
class perimeter
{
public static void main(String[] args)
{
DecimalFormat df = new DecimalFormat("##.00");
Scanner input=new Scanner(System.in);
System.out.println("Enter Area of Square:");
double area=input.nextDouble();
double side=Math.sqrt(area);
System.out.println("Side of Square is: "+df.format(side));
double perimeter=4*side;
System.out.println("Perimeter of Square is: "+df.format(perimeter));
}
}
3. Develop the program calculateCylinderVolume., which accepts radius of a cylinder's base disk and its
height and computes the volume of the cylinder.
/*volume of cylinder*/
import java.util.*;
import java.text.*;
class CalculateCyliderVolume
{
public static double cylinderV(double r,double l)
{
double volume;
volume=3.14*(r*r)*l;
return volume;
}
public static void main(String[] args)
{
DecimalFormat df = new DecimalFormat("##.00");
double PI=3.14;
Scanner input=new Scanner(System.in);
System.out.print("Enter Radius: ");
double r=input.nextDouble();
System.out.print("Enter Height: ");
double h=input.nextDouble();
double volume=PI*r*r*h;
System.out.println("Volume of Cylinder: "+df.format(volume));
}
}
4. Utopias tax accountants always use programs that compute income taxes even though the tax rate is a
solid, never-changing 15%. Define the program calculateTax which determines the tax on the gross pay.
Define calculateNetPay that determines the net pay of an employee from the number of hours worked.
Assume an hourly rate of $12.
/* tax*/
import java.util.*;
import java.text.*;
public class calculatetax
{
public static void main(String[]args)
{
double taxRate=0.15;
double hourlyRate=12;
DecimalFormat df=new DecimalFormat("$##.00");
Scanner input=new Scanner(System.in);
System.out.print("Enter Number of Hours Worked: ");
double hrs=input.nextDouble();
double gp=hrs*hourlyRate;
double tax=gp*taxRate;
double netpay=gp-tax;
System.out.println("Net Pay is: "+df.format(netpay));
}
}
5.An old-style movie theater has a simple profit program. Each customer pays $5 per ticket. Every
performance costs the theater $20, plus $.50 per attendee. Develop the program calculateTotalProfit that
consumes the number of attendees (of a show) and calculates how much income the show earns.
/* income earn calculation*/
import java.util.*;
import java.text.*;
class CalculateTotalProfit
{
public static void main(String[] args)
{
DecimalFormat df=new DecimalFormat("$##.00");
double theaterCost=20;
Scanner input=new Scanner(System.in);
System.out.println("Enter Number of Customers: ");
double cus=input.nextDouble();
double earnFromTickets=5*cus;
double attendeesCost=cus*0.50;
double cost=attendeesCost+theaterCost
;
double profit=earnFromTickets-cost;
System.out.println("Total Profit: "+df.format(profit));
}
}
6.Develop the program calculateCylinderArea, which accepts radius of the cylinder's base disk and its height
and computes surface area of the cylinder.
/*Area of cylinder*/
import java.util.*;
import java.text.*;
class CalculateCylinderArea
{
public static void main(String[] args)
{
DecimalFormat df = new DecimalFormat("##.00");
double pi=3.14;
Scanner input=new Scanner(System.in);
System.out.print("Enter Radius: ");
double r=input.nextDouble();
System.out.print("Enter Height: ");
double h=input.nextDouble();
double v1=2*pi*r*r;
double v2=2*pi*r*h;
double surfaceArea=v1+v2;
System.out.println("Surface Area of Cylinder: "+df.format(surfaceArea));
}
}
7.Develop the program calculatePipeArea. It computes the surface area of a pipe, which is an open cylinder.
The program accpets three values: the pipes inner radius, its length, and the thickness of its wall.
/* calculate pipe area*/
import java.util.*;
class CalculateCyliderVolume
{
public static void main(String[] args)
{
double PI=3.14;
Scanner input=new Scanner(System.in);
System.out.print("Enter Radius: ");
double r=input.nextDouble();
System.out.print("Enter Height: ");
double h=input.nextDouble();
double volume=PI*r*r*h;
System.out.println("Volume of Cylinder: "+volume);
}
}
8. Develop the program calculateHeight, which computes the height that a rocket reaches in a given amount
of time.If the rocket accelerates at a constant rate g, it reaches a speed of g • t in t time units and a height of
1/2 * v * t where v is the speed at t.
Ans:
import java.util.*;
public class calculateHeight {
public static void main(String[] args) {
System.out.println(“Enter the time in seconds : “);
Scanner s=new Scanner(System.in);
double time=s.nextDouble();
double acc;
double g=9.8;
acc=g;
double vel=acc*time;
double h=(vel*time)/2;
System.out.println(“Height reached by the rocket (in km) is : ” +(h/1000));
}
}
9.Develop a program that computes the distance a boat travels across a river, given the width of the river,
the boat's speed perpendicular to the river, and the river's speed. Speed is distance/time, and the
Pythagorean Theorem is c2 = a2 + b2.
/* distance by boat*/
import java.util.*;
import java.text.*;
class DistanceTravelledbyBoat
{
public static void main(String[] args)
{
DecimalFormat df = new DecimalFormat("##.00");
Scanner input=new Scanner(System.in);
System.out.print("Enter width of river: ");
double width=input.nextDouble();
System.out.print("Enter boat's speed perpendicular to river: ");
double boatspeed=input.nextDouble();
System.out.print("Enter river's speed: ");
double riverspeed=input.nextDouble();
double a=width;
double bs=boatspeed;
double c=0;
double t=a/bs;
double rs=riverspeed;
double b=t*rs;
double distance=c*c;
double BB=b*b;
double AA=a*a;
distance=AA+BB;
System.out.println("Distance boat travels: "+df.format(distance));
}
}
10. Develop a program that accepts an initial amount of money (called the principal), a simple annual
interest rate, and a number of months will compute the balance at the end of that time. Assume that no
additional deposits or withdrawals are made and that a month is 1/12 of a year. Total interest is the product
of the principal, the annual interest rate expressed as a decimal, and the number of years.
/*interest calculation*/
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class TotalInterest extends JFrame
{
TotalInterest()
{
JLabel lab1=new JLabel("Principal");
final JTextField text1=new JTextField(20);
JLabel lab2=new JLabel("Rate of Interest");
final JTextField text2= new JTextField(20);
JLabel lab3=new JLabel("Number of Months");
final JTextField text3=new JTextField(20);
JButton b=new JButton("Get");
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
double p=Double.parseDouble(text1.get
Text());
double r=Double.parseDouble(text2.get
Text())/100;
double t=Double.parseDouble(text3.get
Text())/12;
double interest=p*r*t;
JOptionPane.showMessageDialog(
null, "Total Interest is: "+interest);
}
}
setLayout(null);
lab1.setBounds(10,10,100,20);
text1.setBounds(150,10,200,20)
;
lab2.setBounds(10,40,100,20);
text2.setBounds(150,40,200,20)
;
lab3.setBounds(10,70,120,20);
text3.setBounds(150,70,200,20)
;
b.setBounds(150,110,70,20);
add(lab1);
add(text1);
add(lab2);
add(text2);
add(lab3);
add(text3);
add(b);
setVisible(true);
setSize(400,200);
}
public static void main(String[] args)
{
new TotalInterest();
}
}
JAVA ASSIGNMENT 2
1)Create a washing machine class with methods as switchOn, acceptClothes, acceptDetergent, switchOff.
acceptClothes accepts the noofClothes as argument & returns the no of Clothes.
Ans:
import java.util.*;
class WashingMachine{
Scanner input=new Scanner(System.in);
public void switchOn () {
System.out.println ("The washing machine is switched on");
}
public void acceptDetergent () {
System.out.println("Accepting Detergent. ");
}
public int acceptClothes(int a){
return a;
}
public void switchOff () {
System.out.println ("The washing machine is switched off.");
}
public static void main(String[] args){
WashingMachine wm=new WashingMachine();
wm.switchOn();Scanner s=new Scanner(System.in);
System.out.println("Enter no of clothes: ");
int n=s.nextInt();
wm.acceptDetergent();
System.out.println(" finished washing of "+wm.acceptClothes(n)+" clothes");
wm.switchOff();
}
}
—————————————————————————————————————————————–
2)Create a calculator class which will have methods add, multiply, divide & subtract
Ans:
import java.util.*;
import java.io.*;
class Cal{
public double add(double a,double b){
return a+b;
}
public double subtract(double a,double b){
return a-b;
}
public double multiply(double a,double b){
return a*b;
}
public double divide(double a,double b){
return a/b;
}
}
public class Calculator{
public static void main(String []args){
Cal c=new Cal();
System.out.println("enter two numbers");
Scanner s=new Scanner(System.in);
double num1=s.nextDouble();
double num2=s.nextDouble();
System.out.println("Enter choice:\n1.ADD\n2.SUBTRACT\n3.DIVIDE\n4.MULTIPLY\n");
int ch=s.nextInt();double res=0;
switch(ch){
case 1: res=c.add(num1,num2);break;
case 2:res=c.subtract(num1,num2);break;
case 3:res=c.divide(num1,num2);break;
case 4:res=c.multiply(num1,num2);break;
}
System.out.println("The result is: "+res);
}
}
Output:
enter two numbers
3
6
Enter choice:
1.ADD
2.SUBTRACT
3.DIVIDE
4.MULTIPLY
3
The result is: 0.5
——————————————————————————————————————————–
3)Create a class called Student which has the following methods:
i. Average: which would accept marks of 3 examinations & return whether the student has passed or
failed depending on whether he has scored an average above 50 or not.
ii. Inputname: which would accept the name of the student & returns the name.
Ans:
import java.util.*;
import java.io.*;
class Student
{double avg;String name;
public String average(double a,double b,double c)
{
avg=(a+b+c)/3;
if(avg>=50)
{return "passed";
}
else return "failed";
}
public String Inputname(String str)
{
name=str;
return name;
}
}
class average
{
public static void main(String args[])
{Scanner s=new Scanner(System.in);
System.out.println("enter student name: ");
String n=s.nextLine();
System.out.println("enter marks of first subject: ");
double num1=s.nextDouble();
System.out.println("enter marks of second subject: ");
double num2=s.nextDouble();
System.out.println("enter marks of third subject: ");
double num3=s.nextDouble();
Student st=new Student();
String g=st.average(num1,num2,num3);
System.out.println(st.Inputname(n)+" is "+g);
}
}
Output:
enter student name:
silla subhangi
enter marks of first subject:
78
enter marks of second subject:
56
enter marks of third subject:
90
silla subhangi is passed
—————————————————————————————————————————————
4)Create a Bank class with methods deposit & withdraw. The deposit method would accept attributes
amount
& balance & returns the new balance which is the sum of amount & balance. Similarly, the withdraw method
would accept the attributes amount & balance & returns the new balance ‘balance – amount’ if balance > =
amount
or return 0 otherwise.
Ans:
import java.util.*;
import java.io.*;
class Bank{
public double deposit(double amt,double bal)
{
return (amt+bal);
}
public double withdraw(double amt,double bal)
{
if(bal>=amt)
return (bal-amt);
else return 0;
}
}
class atm
{
public static void main(String args[])
{
Scanner s= new Scanner(System.in);
Bank b=new Bank();
System.out.println("enter the amount to deposit");
double a=s.nextDouble();
double bal=0;
double newbal=b.deposit(a,bal);
System.out.println("amount is deposited");
System.out.println("The total balance is: "+newbal);
System.out.println("enter the amount to withdraw");
double am=s.nextDouble();
double ba=b.withdraw(am,newbal);
if(ba==0){System.out.println("no sufficient balance to withdraw");}
else{
System.out.println("the amount is withdrawn");
System.out.println("the balance is "+ba);
}
}
}
Output:
enter the amount to deposit
200
amount is deposited
The total balance is: 200.0
enter the amount to withdraw
100
the amount is withdrawn
the balance is 100.0
——————————————————————————————————————————
5)Create an Employee class which has methods netSalary which would accept salary & tax as arguments &
returns the netSalary which is tax deducted from the salary. Also it has a method grade which would accept
the grade of the employee & return grade.
Ans:
import java.util.*;
import java.io.*;
class Employee{
public double netsalary(double sal,double tax)
{
return (sal-(sal*tax/100));
}
public String grade(String empgrade){
return empgrade;
}
}
class tax
{public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.println("enter grade of employee");
String str=s.nextLine();
System.out.println("enter the salary ");
double sa=s.nextDouble();
System.out.println("enter tax in percentage");
double t=s.nextDouble();
Employee e=new Employee();
double finsal=e.netsalary(sa,t);
System.out.println("The net salary of "+e.grade(str)+" grade employee is: "+finsal);
}
}
Output:
enter grade of employee
A
enter the salary
26000
enter tax in percentage
15
The net salary of A grade employee is: 22100.0
———————————————————————————————————————————
6)Create Product having following attributes: Product ID, Name, Category ID and UnitPrice. Create
ElectricalProduct having the following additional attributes: VoltageRange and Wattage. Add a behavior to
change the Wattage and price of the electrical product. Display the updated ElectricalProduct details.
Ans:
import java.util.*;
import java.io.*;
class Product
{
int productID;
String name;
int categoryID;
double price;
Product(int productID,String name,int categoryID,double price){
this.productID=productID;this.name=name;this.categoryID=categoryID;this.price=price;
}
public void display1()
{
System.out.println("product id= "+productID);
System.out.println("product name= "+name);
System.out.println("category id= "+categoryID);
System.out.println("price= "+price);
}
}
class ElectricalProduct extends Product{
double voltageRange;
double wattage;
ElectricalProduct(int productID,String name,int categoryID,double price,double voltageRange,
double wattage){
super(productID,name,categoryID,price);
this.voltageRange=voltageRange;
this.wattage=wattage;
}
public void display()
{
super.display1();
System.out.println("voltage range= "+voltageRange+" Volts”);
System.out.println("wattage= "+wattage+ "watts");
}
}
class pro
{
public static void main(String args[])
{
ElectricalProduct ep=new ElectricalProduct(1,”bulb”,2,80,20,60);
ep.display();
}
}
Output:
product id= 1
product name= bulb
category id= 2
price= 80.0
voltage range= 20.0 Volts
wattage= 60.0watts
————————————————————————————————————————————
7)Create Book having following attributes: Book ID, Title, Author and Price. Create Periodical which has
the following additional attributes: Period (weekly, monthly etc…) .Add a behavior to modify the Price and
the Period of the periodical. Display the updated periodical details.
Ans:
import java.util.*;
class Book{
int BookID=1;;
double Price;
String Title="java";String Author="Herbit Schildt";
}
class Periodical extends Book{
String Period;
public void display(){
System.out.println("Book id = "+(BookID));
System.out.println("\nprice="+(Price));
System.out.println("\ntitle is "+(Title));
System.out.println("\nauthor is "+(Author));
System.out.println("\nperiod="+(Period));
}
}
class mag
{public static void main(String args[]){
Scanner s=new Scanner(System.in);
Periodical p=new Periodical();
System.out.println("Enter the period of book : ");
p.Period= s.nextLine ();
System.out.println("Enter the price of book : ");
p.Price=s.nextInt();
p.display();
}}
Output:
Enter the period of book :
yearly
Enter the price of book :
900
Book id = 1
price=900.0
title is java
author is Herbit Schildt
period=yearly
————————————————————————————————————————————-
8)Create Vehicle having following attributes: Vehicle No., Model, Manufacturer and Color. Create truck
which has the following additional attributes:loading capacity( 100 tons…).Add a behavior to change the
color and loading capacity. Display the updated truck details.
Ans:
import java.util.*;
class Vehicle{
int vehnum=1;
String model="XYz13",manfr="tata",color;
}
class Truck extends Vehicle{
String capacity;
public void display(){
System.out.println("vehicle number = "+vehnum);
System.out.println("\nmodel="+model);
System.out.println("\nmanufacturer= "+manfr);
System.out.println("\ncolor is "+color);
System.out.println("\nloading capacity="+capacity);
}
}
class vehtruck
{public static void main(String args[]){
Scanner s=new Scanner(System.in);
Truck p=new Truck();
System.out.println("Enter the color : ");
p.color= s.nextLine ();
System.out.println("Enter the loading capacity: ");
p.capacity=s.nextLine();
p.display();
}}
Output:
Enter the color :
white
Enter the loading capacity:
200 tonnes
vehicle number = 1
model=XYz13
manufacturer= tata
color is white
loading capacity=200 tonnes
———————————————————————————————————————————
9)Write a program which performs to raise a number to a power and returns the value. Provide a behavior
to the program so as to accept any type of numeric values and returns the results.
Ans:
import java.util.*;
class poWer
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
System.out.print("Enter Number: ");
double num=input.nextDouble();
System.out.print("Raise Number’s power: ");
double pow=input.nextDouble();
double value=Math.pow(num,pow);
System.out.println("Result is: "+(value));
}
}
Output:
Enter Number: 2
Raise Number’s power: 3
Result is: 8.0
———————————————————————————————————————————10)Write a function Model-of-Category for a Tata motor dealers, which accepts category of car customer
islooking for and returns the car Model available in that category. the function should accept the following
categories “SUV”, “SEDAN”, “ECONOMY”, and “MINI” which in turn returns “TATA SAFARI” ,
“TATA INDIGO” , “TATA INDICA” and “TATA NANO” respectively.
Ans:
import java.util.*;
class clrt{
static String Model_of_category(String Category){
String cat[]={“SUV”,”SEDAN”,”ECONOMY”,”MINI”};
String model[]={“TATA SAFARI”,”TATA INDIGO”,”TATA INDICA”,”NANO”};
String str=”";
for(int i=0;i<Category.length();i++)
{if(Category.equals(cat[i]))
{str=model[i];
break;
}
}
return str;
}
public static void main(String args[])
{
System.out.println(“enter any category from the following:\n”);
System.out.println(“SUV SEDAN ECONOMY MINI”);
Scanner s=new Scanner(System.in);
String Catg=s.nextLine();
String category=TATA.Model_of_category(Catg);
System.out.println(category);
}
}
Output:
enter any category from the following:
SUV SEDAN ECONOMY MINI
SUV
TATA SAFARI
Related documents