0% found this document useful (0 votes)
9 views

java 7-12

The document outlines multiple Java programs, including a Patient class for tracking vital statistics, a Calculator class for power calculations, and an InputExceptionHandle class for handling exceptions during user input. It also includes a SalesPersons thread, a Student Attendance Management System using HashMap, and a method to count specific index pairs in an array. Each program demonstrates different Java concepts such as exception handling, threading, and data structures.

Uploaded by

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

java 7-12

The document outlines multiple Java programs, including a Patient class for tracking vital statistics, a Calculator class for power calculations, and an InputExceptionHandle class for handling exceptions during user input. It also includes a SalesPersons thread, a Student Attendance Management System using HashMap, and a method to count specific index pairs in an array. Each program demonstrates different Java concepts such as exception handling, threading, and data structures.

Uploaded by

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

Program 7.

Design a class that can be used by a health care professional to keep track of a patient’s vital
statistics. Here’s what the class should do:
1. Construct a class called Patient
2. Store a String name for the patient
3. Store weight and height for patient as doubles
4. Construct a new patient using these values
5. Write a method called BMI which returns the patient’s BMI as a double. BMI can be
calculated as BMI = (Weight in Pounds / ( Height in inches x Height in inches ) ) x 703
6. Next, construct a class called “Patients” and create a main method.
Create a Patient object and assign some height and weight to that object. Display the BMI of
that patient.
Patient.java

package com.nhce.program1a;
public class Patient
{
String patient_name;
double weight;
double height;

Patient(String name, double wt, double ht)


{
patient_name=name;
weight=wt;
height=ht;
}
double BMI()
{
return (weight/(height*height))*703;
}
}

Patients.java

package com.nhce.program1a;
public class Patients {

public static void main(String[] args) {

Patient patient_1 = new Patient("Hari", 78.4, 51);

System.out.println("BMI of Patient: "+ patient_1.patient_name+" is "+patient_1.BMI());


Patient patient_2 = new Patient("Ram", 79.4, 67);
System.out.println("BMI of Patient: "+ patient_2.patient_name+" is "+patient_2.BMI());
}
}
Output
BMI of Patient: Hari is 21.190003844675125
BMI of Patient: Ram is 12.434439741590555
Program 8.

Create a class in Java called “Calculator” which contains the following:

1. A static method called powerInt(int num1,int num2) that accepts two integers and returns
num1 to the power of num2 (num1 power num2).
2. A static method called powerDouble(double num1,int num2) that accepts one double and
one integer and returns num1 to the power of num2 (num1 power num2).
3. Call your method from another class without instantiating the class (i.e. call it like
Calculator.powerInt(12,10) since your methods are defined to be static).
Hint: Use Math.pow(double,double) to calculate the power.

package lab8;
import java.lang.Math;

class calp{

static int powInt_withinotherclass(int a,int b)


{
double a1 = a;
double a2= b;
double x;
x= Math.pow(a1,a2);
int x1 =(int)x;
return x1;

public class calpower {

static int powerInt(int a,int b)


{
double a1 = a;
double a2= b;
double x;
x= Math.pow(a1,a2);
int x1 =(int)x;
return x1;

static double powerdouble(double a,int b )


{
//double a1 = a;
double a2= b;
double x;
x= Math.pow(a,a2);
//int x1 =(int)x;
return x;

// driver code
public static void main(String args[])
{

int w;
w= powerInt(2,3);
System.out.println("CASE - 1 :");
System.out.println("static method called that accepts two integers ");
System.out.println(w);
double w1;
w1 = powerdouble(2.2,3);
System.out.println("CASE-2 :");
System.out.println("static method called that accepts one double and one
integer ");
System.out.println(w1);
System.out.println("CASE-3 :");
System.out.println("static method called from other class");
System.out.println(calp.powInt_withinotherclass(4,3));

}
}

Program 9.

Write a Program to take care of Number Format Exception if user enters values other than
integer for calculating average marks of 2 students. The name of the students and marks in 3
subjects are taken from the user while executing the program. In the same Program write your
own Exception classes to take care of Negative values and values out of range (i.e.
other than in the range of 0-100). Include finally to output the statement “Program
terminated”.

InputExceptionHandle.java
package com.nhce.program2a;
import java.util.Scanner;

public class InputExceptionHandle {


public static void main(String[] args) {
String student1_name,student2_name;
int student1_marks[]= new int[3];
int student2_marks[]= new int[3];
int sum1=0,sum2=0;
float avg_marks;
Scanner in = new Scanner(System.in);
try{
System.out.println("Enter Student1 Name: ");
student1_name = in.nextLine();
for(int i=0;i<3;i++)
{
System.out.println("Enter Student1 mark" + (i+1) +" :");
student1_marks[i]=Integer.parseInt(in.next());
if(student1_marks[i]<0 || student1_marks[i]>100)
throw new MarksValidationException("Marks entered are negative or outside the range (0-
100)");
sum1=sum1 + student1_marks[i];
}
System.out.println("Enter Student2 Name: ");
student2_name = in.next();
for(int i=0;i<3;i++)
{
System.out.println("Enter Student1 mark" + (i+1) +" :");
student2_marks[i]=Integer.parseInt(in.next());
if(student2_marks[i]<0 || student2_marks[i]>100)
msg
throw new MarksValidationException("Marks entered are negative or outside the range (0-
100)");
sum2=sum2 + student2_marks[i];
}

avg_marks=(sum1+sum2)/6;
System.out.println("The average marks of "+ student1_name + " and " + student2_name + "
is " + avg_marks);
} msg
catch(NumberFormatException e)
{ System.out.println("Entered input is not a valid format for an integer" + e); }
catch(MarksValidationException e)
{ System.out.println(e.toString()); }
finally
{
in.close();
System.out.println("Program terminated!!!");
}

}
}
MarksValidationException.java

package com.nhce.program2a;
public class MarksValidationException extends Exception {
String msg;

MarksValidationException(String msg){
this.msg=msg;
}

public String toString()


{
return(msg);
}
}

Output
Enter Student1 Name:
vandana
Enter Student1 mark1 :
Fdgdghd
Entered input is not a valid format for an integer

-12
Enter Student1 mark2 :
105
Marks entered are negative or outside the range (0-100)
Program terminated!!!

Program 10

Create class of SalesPersons as a thread that will display fives sales persons name. Create a
class as Days as other Thread that has array of seven days. Call the instance of SalesPersons
in Days and start both the Threads. Suspend SalesPersons on Sunday and resume on the day
Wednesday.

Days.java
package com.nhce.program3a;

public class Days implements Runnable {

static String[] weekDays = new


String[]{"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
public void run() {
SalesPersons sales = new SalesPersons();
sales.start();

for(int i=0;i<7;i++)
{
if(weekDays[i].equals("Sunday"))

{ System.out.println("suspended sales thread");


sales.suspend();

if(weekDays[i].equals("Wednesday"))
{
sales.resume();
System.out.println("resuming sales thread");
}
}

public static void main(String args[])


{

Days days= new Days();


Thread DaysThread = new Thread(days);
System.out.println("Starting Days Thread");
DaysThread.start();
}
}

SalesPersons.java
package com.nhce.program3a;
public class SalesPersons extends Thread {

String salesperson[] = new String[] { "Hari","Ram","John","Tom","Joseph"};

public void run()


{
System.out.println("Staring SalesPerson Thread");
for(int i=0;i<5;i++)
System.out.println("SalesPerson" + (i+1) +" : " + salesperson[i]);
try {
sleep(1000);
} catch (InterruptedException e) {
//e.printStackTrace();
}
}
}
Program 11

Create a Student Attendance Management System using aHashMapCollection type. Perform


the following operations:
Add the key-value pair.
Retrieve the value associated with a given key
Check whether a particular key/value exist.
replace a value associated with a given key in the HashMap

import java.util.HashMap;

public class StudentAttendanceManagementSystem {

// HashMap to store student names as keys and attendance as values

private HashMap<String, Integer> attendanceMap;

// Constructor

public StudentAttendanceManagementSystem() {

attendanceMap = new HashMap<>();

// Method to add a key-value pair

public void addStudent(String name, int attendance) {

attendanceMap.put(name, attendance);

// Method to retrieve the value associated with a given key

public Integer getAttendance(String name) {

return attendanceMap.get(name);

// Method to check whether a particular key exists


public boolean containsStudent(String name) {

return attendanceMap.containsKey(name);

// Method to check whether a particular value exists

public boolean containsAttendance(int attendance) {

return attendanceMap.containsValue(attendance);

// Method to replace a value associated with a given key

public void replaceAttendance(String name, int newAttendance) {

if (attendanceMap.containsKey(name)) {

attendanceMap.put(name, newAttendance);

} else {

System.out.println("Student not found.");

// Main method to demonstrate the usage

public static void main(String[] args) {

StudentAttendanceManagementSystem sams = new StudentAttendanceManagementSystem();

// Add students

sams.addStudent("Alice", 5);

sams.addStudent("Bob", 3);

sams.addStudent("Charlie", 4);
// Retrieve attendance

System.out.println("Alice's attendance: " + sams.getAttendance("Alice")); // Output: 5

// Check if a student exists

System.out.println("Is Bob in the system? " + sams.containsStudent("Bob")); // Output: true

// Check if a particular attendance value exists

System.out.println("Is there a student with 3 days of attendance? " +


sams.containsAttendance(3)); // Output: true

// Replace attendance value

sams.replaceAttendance("Alice", 6);

System.out.println("Alice's new attendance: " + sams.getAttendance("Alice")); // Output: 6

// Try to replace attendance for a non-existent student

sams.replaceAttendance("David", 4); // Output: Student not found.

Program 12

Develop a program to solve the problem given:


An array of length N is provided. Count the number of (i,j) pairs where 1<=i<j<=N such that the
difference of the array elements on that indices is equal to the sum of the square of their indices.
Input : 4, 9, 6, 29, 30
Output: 3
(1,2), (2,4),(1,5) satisfy the above condition

public class CountPairs {


public static void main(String[] args) {

int[] array = {4, 9, 6, 29, 30};

int result = countPairs(array);

System.out.println(result);

public static int countPairs(int[] arr) {

int count = 0;

int n = arr.length;

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

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

int diff = arr[j] - arr[i];

int indexSum = (j + 1) * (j + 1) - (i + 1) * (i + 1);

if (diff == indexSum) {

count++;

return count;

The countPairs method takes an array as input and iterates over all pairs of indices (i, j) where
1 <= i < j <= N. For each pair, it calculates the difference between the array elements at those
indices and the sum of the squares of the indices. If the difference is equal to the index sum, it
increments the count. In the main method, we provide the example array [4, 9, 6, 29, 30] and
print the result.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy