Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

JAVA programslab

The document contains multiple Java programs covering various topics including prime number generation, solving quadratic equations, creating pyramids, managing bank accounts, temperature analysis, election voting, merging and sorting arrays, calculating cube properties, generating Fibonacci numbers, and managing student scores. Each program is structured with classes and methods to perform specific tasks, demonstrating fundamental programming concepts. The document serves as a comprehensive guide for Java programming exercises.

Uploaded by

Riddhi Gayathri
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

JAVA programslab

The document contains multiple Java programs covering various topics including prime number generation, solving quadratic equations, creating pyramids, managing bank accounts, temperature analysis, election voting, merging and sorting arrays, calculating cube properties, generating Fibonacci numbers, and managing student scores. Each program is structured with classes and methods to perform specific tasks, demonstrating fundamental programming concepts. The document serves as a comprehensive guide for Java programming exercises.

Uploaded by

Riddhi Gayathri
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Java programs

1. A) Prime numbers

class PrimeNumbers {
public static void main(String args[]) {
int prime;
int n1 = Integer.parseInt(args[0]);
int n2 = Integer.parseInt(args[1]);
System.out.println("Prime numbers in the given range are:");
for (int i = n1; i <= n2; i++) {
prime = 1;
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
prime = 0;
break;
}
}
if (prime == 1)
System.out.println(i + " ");
}
}
}

b)Quadratic equation

class QuadraticEquation {
public static void main(String[] args) {
double a = Double.parseDouble(args[0]);
double b = Double.parseDouble(args[1]);
double c = Double.parseDouble(args[2]);
double disc = b * b - 4 * a * c;
double sqrt = Math.sqrt(disc);

if (disc > 0) {
double root1 = (-b + sqrt) / (2 * a);
double root2 = (-b - sqrt) / (2 * a);
System.out.println("Roots are: " + root1 + " and " + root2);
} else if (disc == 0) {
double root = -b / (2 * a);
System.out.println("Root is: " + root);
} else {
System.out.println("Roots are imaginary.");
}
}
}
C)Pyramid

class Pyramid {
public static void main(String args[]) {
int n = Integer.parseInt(args[0]);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*\t");
System.out.println();
}
}
}

2)Bank account

import java.util.*;
class Account {
private int AccNo;
private String name;
private double balance;
private String AccType;
Scanner sc = new Scanner(System.in);

Account() {
AccNo = 0;
name = "";
balance = 0.0;
AccType = "";
}

void getDetails() {
System.out.print("Enter account holder's name: ");
name = sc.next();
System.out.print("Enter Account Number: ");
AccNo = sc.nextInt();
System.out.print("Enter the balance amount: ");
balance = sc.nextDouble();
System.out.print("Enter account type: ");
AccType = sc.next();
}

void printDetails() {
System.out.println("Acc No\tName\tBalance amount\tType of account");
System.out.println(AccNo + "\t\t" + name + "\t\t" + balance + "\t\t" + AccType);
}

void deposit() {
double amt;
System.out.print("\nEnter the amount to be deposited: ");
amt = sc.nextDouble();
balance += amt;
System.out.print("\nAmount deposited successfully....\nCurrent Balance: " + balance);
}

void withdrawal() {
double amt;
System.out.print("\nEnter the amount to be withdrawn: ");
amt = sc.nextDouble();
if (balance >= amt) {
balance -= amt;
System.out.print("Transaction successful......\nCurrent Balance: " + balance);
} else {
System.out.print("\nInsufficient balance in account....\nTransaction failed.....");
}
}

boolean search(int acn) {


if (AccNo == acn) {
printDetails();
return true;
}
return false;
}
}

public class _2ExecuteAccount {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("\nEnter the number of account holders: ");
int n = sc.nextInt();
Account[] holder = new Account[n];

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


holder[i] = new Account();
System.out.println("For Account~" + (i + 1) + " >>>");
holder[i].getDetails();
}

int choice;
do {
System.out.println(
"\n\n********* Main Menu **********\n\nEnter\n1. To display all details of account
holder");
System.out.println("2. Search details by account number\n3. To deposit amount\n4. To withdraw the
amount");
System.out.println("5. To exit from the program\n");

System.out.print("Enter your Choice: ");


choice = sc.nextInt();

switch (choice) {
case 1:
for (int i = 0; i < n; i++)
holder[i].printDetails();
break;
case 2:
System.out.print("\nEnter the account number: ");
int acn = sc.nextInt();
boolean found = false;
for (int i = 0; i < n; i++) {
found = holder[i].search(acn);
if (found)
break;
}
if (!found) {
System.out.print("\nSearch failed.....\nAccount doesn't exists");
}
break;

case 3:
System.out.print("\nEnter the account number: ");
int ac = sc.nextInt();
boolean dep = false;
for (int i = 0; i < n; i++) {
dep = holder[i].search(ac);
if (dep) {
holder[i].deposit();
break;
}
}
if (!dep) {
System.out.print("\nSearch failed....\nAccount doesn't exits");
}
break;

case 4:
System.out.print("\nEnter account number: ");
int acc = sc.nextInt();
boolean fou = false;
for (int i = 0; i < n; i++) {
fou = holder[i].search(acc);
if (fou) {
holder[i].withdrawal();
break;
}
}
if (!fou) {
System.out.print("\nSearch failed.....\nAccount doesn't exists");
}
break;

case 5:
System.out.print("Thank you.....");
break;
}

} while (choice != 5);


// sc.close();
}
}
3)TEMPERATURE
import java.util.Scanner;

class Temp {
static int i, j;

public static void main(String[] args) {


Scanner input = new Scanner(System.in);
String[] city = { "city 1", "city 2", "city 3", "city 4", "city 5" };
float[][] temp = new float[5][6];

for (i = 0; i < 5; i++) {


System.out.println("Enter the temperature for " + city[i]);
for (j = 0; j < 6; j++) {
temp[i][j] = input.nextFloat();
}
}

float maxTemp = temp[0][0];


float minTemp = temp[0][0];
String maxCity = city[0];
String minCity = city[0];

for (i = 0; i < 5; i++) {


for (j = 0; j < 6; j++) {
if (temp[i][j] > maxTemp) {
maxTemp = temp[i][j];
maxCity = city[i];
}
if (temp[i][j] < minTemp) {
minTemp = temp[i][j];
minCity = city[i];
}
}
}

System.out.println("City with highest temperature is " + maxCity + " with " + maxTemp + " Celsius.");
System.out.println("City with lowest temperature is " + minCity + " with " + minTemp + " Celsius.");
}
}

4)ELECTION

import java.util.*;
class Vote {
Scanner s = new Scanner(System.in);
int voter_id;
static int count[] = new int[6];
int ballot;
void read() {
System.out.print("Enter the voter ID: ");
voter_id = s.nextInt();

System.out.print("Enter the ballot of your choice: ");


ballot = s.nextInt();
}

void calculateVotes() {
switch (ballot) {
case 1: count[1] += 1; break;
case 2: count[2] += 1; break;
case 3: count[3] += 1; break;
case 4: count[4] += 1; break;
case 5: count[5] += 1; break;
default: count[0] += 1; break;
}
}

static void display() {


System.out.println("\t\tElection Result\n");
System.out.println("Total number of votes for each candidate is as follows:");
for (int i = 1; i <= 5; i++) {
System.out.println("Candidate " + i + " votes: " + count[i]);
}
System.out.println("Spoiled ballots: " + count[0]);
}
}

class Election {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of voters: ");
int n = sc.nextInt();

Vote[] voters = new Vote[n];


for (int i = 0; i < n; i++) {
voters[i] = new Vote();
System.out.println("Voter " + (i + 1) + ":");
voters[i].read();
voters[i].calculateVotes();
}
Vote.display();
}
}

5)ARRAY

import java.util.Arrays;
import java.util.Scanner;
class MergeArray {
int[] array1;
int[] array2;

MergeArray()
{}
MergeArray(int[] a, int[] b) {
array1 = a;
array2 = b;
}

public int[] merging() {


int aLength = array1.length;
int bLength = array2.length;
int[] c = new int[aLength + bLength];

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


c[i] = array1[i];
}

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


c[aLength + i] = array2[i];
}
return c;
}

public int[] sortArray(int[] A) {


Arrays.sort(A); // Sorts in ascending order
return A;
}

public void displayArray(int[] A) {


for (int i : A) {
System.out.print(i + " ");
}
System.out.println();
}

public int[] takeInput(String statement, Scanner scanner) {


System.out.println(statement);
int n = scanner.nextInt(); // Size of the array
int[] arr = new int[n];

System.out.println("Enter " + n + " elements in unsorted order:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
return arr;
}

public static void main(String[] args) {


MergeArray Obj1 = new MergeArray();
MergeArray Obj2 = new MergeArray();
Scanner input = new Scanner(System.in);
int[] a = Obj1.takeInput("Enter the number of elements for the first array:", input);
int[] b = Obj2.takeInput("Enter the number of elements for the second array:", input);

MergeArray Obj = new MergeArray(a, b);


int[] d = Obj.merging();

int[] sortedArray = Obj.sortArray(d);

System.out.print("Sorted Merged Array: ");


Obj.displayArray(sortedArray);
}
}

6) A)CUBE
import java.util.Scanner;
class Cube {
float a;
void read(Scanner scanner) {
System.out.print("Enter the value of the side of the cube: ");
a = scanner.nextFloat();
}
void volume() {
float v = a * a * a;
System.out.println("The volume is: " + v);
}
void area() {
float area = 6 * a * a;
System.out.println("The area is: " + area);
}
}

public class Main {


public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Cube A = new Cube();
Cube B = new Cube();
Cube C = new Cube(); System.out.println("For Cube A:");
A.read(s);
A.volume();
A.area();
System.out.println("For Cube B:");
B.read(s);
B.volume();
B.area();
System.out.println("For Cube C:");
C.read(s);
C.volume();
C.area();
s.close();
}
}
B)FIBONAACI NUMBERS
class FibonacciSeries {
public static void main(String args[]) {
int n = Integer.parseInt(args[0]);
int f1 = 0, f2 = 1, f = 0;
System.out.println("Fibonacci series up to " + n + ":");
for (int i = 1; i <= n; i++) {
System.out.println(f + " ");
f1 = f2;
f2 = f;
f = f1 + f2;
}
}
}

7)Student SCORE
import java.util.*;
class Student {
int rollNumber;

void readNumber(int n) {
rollNumber = n;
}

void printNumber() {
System.out.println("Roll No: " + rollNumber);
}
}

class Test extends Student {


int sub1, sub2, sub3;

void readMarks(int m1, int m2, int m3) {


sub1 = m1;
sub2 = m2;
sub3 = m3;
}

void printMarks() {
System.out.println("Marks in Subject 1: " + sub1);
System.out.println("Marks in Subject 2: " + sub2);
System.out.println("Marks in Subject 3: " + sub3);
}
}

class Results extends Test{


double total;

Void display(){
total = sub1+sub2+sub3;
PrintNumber();
PrintMarks();
System.out.println(“Total score:”+total);
}
}

public class StudentScore{


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.print("Enter the number of students: ");


int n = sc.nextInt();

Results [] students = new Results[n];

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


students[i] = new Results();
System.out.println("Enter details for student " + (i + 1) +);
System.out.print("Enter Roll Number: ");
int roll = sc.nextInt();
students[i].readNumber(roll);

System.out.print("Enter marks for Subject 1: ");


int m1 = sc.nextInt();
System.out.print("Enter marks for Subject 2: ");
int m2 = sc.nextInt();
System.out.print("Enter marks for Subject 3: ");
int m3 = sc.nextInt();
students[i].readMarks(m1, m2, m3);
}

int highSub1 = students[0].sub1, highSub2 = students[0].sub2, highSub3 = students[0].sub3;


int highRollSub1 = students[0].rollNumber, highRollSub2 = students[0].rollNumber, highRollSub3 =
students[0].rollNumber;
int highTotal = students[0].sub1 + students[0].sub2 + students[0].sub3;
int highRollTotal = students[0].rollNumber;

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


int total = students[i].sub1 + students[i].sub2 + students[i].sub3;

if (students[i].sub1 > highSub1) {


highSub1 = students[i].sub1;
highRollSub1 = students[i].rollNumber;
}
if (students[i].sub2 > highSub2) {
highSub2 = students[i].sub2;
highRollSub2 = students[i].rollNumber;
}
if (students[i].sub3 > highSub3) {
highSub3 = students[i].sub3;
highRollSub3 = students[i].rollNumber;
}
if (total > highTotal) {
highTotal = total;
highRollTotal = students[i].rollNumber;
}
}

System.out.println("Highest marks in Subject 1: " + highSub1 + " (Roll No: " + highRollSub1 + ")");
System.out.println("Highest marks in Subject 2: " + highSub2 + " (Roll No: " + highRollSub2 + ")");
System.out.println("Highest marks in Subject 3: " + highSub3 + " (Roll No: " + highRollSub3 + ")");
System.out.println("Highest total marks: " + highTotal + " (Roll No: " + highRollTotal + ")");

sc.close();
}
}

8)BOOK DETAILS
import java.util.Scanner;

class Book {
Scanner sc = new Scanner(System.in);

String name;
int code, quantity;
double unitPrice, totalPrice;

void inputData() {
System.out.print("Enter the name of the Book: ");
name = sc.nextLine();
System.out.print("Enter the code of Book: ");
code = sc.nextInt();
System.out.print("Enter the Price of Book: ");
unitPrice = sc.nextDouble();
System.out.print("Enter the number of Books: ");
quantity = sc.nextInt();

totalPrice = quantity * unitPrice;


}

void outputData() {
System.out.println(name + "\t" + code + "\t" + unitPrice + "\t\t" + quantity + "\t\t" + totalPrice);
}
}

public class GetBookDetails {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.print("Enter the number of Books: ");


int u = sc.nextInt();

Book[] books = new Book[u];


for (int i = 0; i < u; i++) {
books[i] = new Book();
System.out.println("\nEnter the details of Book- " + (i + 1));
books[i].inputData();
}

System.out.println("\nName\tCode\tUnitPrice\tQuantity\tTotalPrice");
for (int i = 0; i < u; i++)
books[i].outputData();

sc.close();
}
}
9)EMPLOYEE DETAILS

import java.util.Scanner;
class Employee {
Scanner sc = new Scanner(System.in);
private String ID;
private String name;
private String department;
private double basicPay;
private double grossPay;
private double netPay;
private double totalTax;

void readDetails() {
System.out.print("Enter employee-ID: ");
ID = sc.nextLine();
System.out.print("Enter name: ");
name = sc.nextLine();
System.out.print("Enter department: ");
department = sc.nextLine();
System.out.print("Enter basic pay: ");
basicPay = sc.nextDouble();
sc.close();
grossPay = computeGrossPay();
netPay = computeNetPay();
}

double computeGrossPay() {
double DA = (0.58 * basicPay);
double HRA = (0.16 * basicPay);
return (basicPay + DA + HRA);
}

double computeNetPay() {
if (grossPay <= 200000) {
totalTax = 0;
} else if (grossPay <= 300000) {
totalTax = (0.10 * grossPay);
} else if (grossPay <= 500000) {
totalTax = (.15 * grossPay);
} else {
double tax = (.30 * grossPay);
totalTax = (tax + (0.02 * tax));
}
return (grossPay - totalTax);
}

void displayDetails() {
System.out.println(name + "\t" + ID + "\t" + department + "\t" + basicPay + "\t" + totalTax + "\t" + netPay);
}
}

public class EmployeeDetails {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of employees in a company: ");
int numberOfEmployees = sc.nextInt();

// Declaring an array that holds details of Employee type objects


Employee[] employeeDetails = new Employee[numberOfEmployees];

// Reading details of N employees


for (int i = 0; i < numberOfEmployees; i++) {
employeeDetails[i] = new Employee();
System.out.println("\nEnter details of Employee-" + (i + 1));
employeeDetails[i].readDetails();
}
sc.close();

// Displaying details of N employees


System.out.println("\n\t\t\t***Details of Employees*");
System.out.println("Name\tID\t Department\tBasic Pay\tIncome Tax\tNet Pay");
for (int i = 0; i < numberOfEmployees; i++) {
employeeDetails[i].displayDetails();
}
}
}

10)BANK DETAILS

import java.util.*;
abstract class Bank {
char bankType;
double amount, interest;
boolean platinumCard;
boolean offerCreditCard;

abstract void getRoi();


void deposit() {
bankType = 'v';
amount = 0.00;
interest = 0.0;
platinumCard = false;
}
}

class BankDetails extends Bank {


Scanner sc = new Scanner(System.in);
double termDeposit = 0;
int term = 0;

void getRoi() {
if (bankType == 'n') {
platinumCard = false;
if (term >= 3)
interest = 0.07 * termDeposit*term;
} else {
platinumCard = true;
if (term >= 3)
interest = 0.08 * termDeposit*term;
}
}
@Override
void deposit() {
System.out.println("Enter the type of bank\n'n' - for Nationalised Bank \n'i' - for International Bank ");
bankType = sc.next().charAt(0);
if (bankType == 'n' || bankType == 'i') {
System.out.print("Enter the amount to be deposited in the bank: ");
termDeposit = sc.nextDouble();
System.out.print("Enter the term for which amount has been deposited (in years): ");
term = sc.nextInt();
getRoi();
} else
System.out.println("Invalid Bank type!");
}

void display() {
String bank;
if (bankType == 'n')
bank = "Nationalised Bank";
else if (bankType == 'i')
bank = "International Bank";
else
bank = "Invalid Bank type";

System.out.println("Type of Bank: " + bank);


System.out.println("Amount deposited :Rs."+termDeposit+" for "+term+" years");
System.out.print("Interest accrued over "+term+" years: Rs." );
System.out.printf("%.3f%n",interest);
if (platinumCard)
System.out.println("Eligible for platinum card");
else
System.out.println("Not eligible for platinum card");
}

public static void main(String[] args) {


try (Scanner sc = new Scanner(System.in)) {
System.out.print("Enter number of banks: ");
int n = sc.nextInt();
BankDetails[] bank = new BankDetails[n];

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


bank[i] = new BankDetails();
System.out.println("Enter the details of Bank " + (i + 1) + ": ");
bank[i].deposit();
}

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


System.out.println("\n\n______________________________\nDetails of Bank " + (i + 1) + ": ");
bank[i].display();
}
}
}
}
11)STUDENT SCORE
import java.util.Scanner;

class Student {
int rollNumber;

void readNumber(int n) {
rollNumber = n;
}

void printNumber() {
System.out.println("Roll No: " + rollNumber);
}
}

class Test extends Student {


int sub1, sub2;

void readMarks(int m1, int m2) {


sub1 = m1;
sub2 = m2;
}

void printMarks() {
System.out.println("Marks in Subject-1: " + sub1);
System.out.println("Marks in Subject-2: " + sub2);
}
}

interface Sports {
void readWt(double n);

void printWt();
}

class Results extends Test implements Sports {


double total, sportWt;

public void readWt(double n) {


sportWt = n;
}

public void printWt() {


System.out.println("Sports Weightage: " + sportWt);
}

void display() {
total = sub1 + sub2 + sportWt;
printNumber();
printMarks();
printWt();
System.out.println("Total Score: " + total);
}
}

public class StudentScore {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int n = sc.nextInt();
Results[] students = new Results[n];

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


students[i] = new Results();
System.out.println("\nEnter details of student-" + (i + 1));
System.out.print("Roll Number: ");
students[i].readNumber(sc.nextInt());
System.out.print("Subject-1 Marks: ");
int m1 = sc.nextInt();
System.out.print("Subject-2 Marks: ");
int m2 = sc.nextInt();
students[i].readMarks(m1, m2);
System.out.print("Sports Weightage: ");
students[i].readWt(sc.nextDouble());
}

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


System.out.println("\nDetails of Student-" + (i + 1) + " ~");
students[i].display();
}
sc.close();
}
}

12)STACK IMPLEMENTATION

import java.util.*;
class StackException extends Exception {
StackException(String str) {
super(str);
}
}

class Stack {
private final int[] stk;
private int tos;

Stack(int size) {
stk = new int[size];
tos = -1;
}

void push(int item) throws StackException {


if (tos == stk.length - 1)
throw new StackException("Stack Overflow!");
else
stk[++tos] = item;
}

int pop() throws StackException {


if (tos < 0)
throw new StackException("Stack Underflow!");
else
return stk[tos--];
}

void display() {
if (tos > -1) {
System.out.print("Stack elements are: ");
for (int i = tos; i > -1; i--)
System.out.print(stk[i] + " ");
} else
System.out.println("Stack Underflow!\n");
}

void peek() {
if (tos == -1)
System.out.println("Stack Underflow!\n");
else
System.out.println("Peek element : " + stk[tos]);
}
}

public class StackImplementation {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the stack size: ");
int size = sc.nextInt();
Stack stkObj = new Stack(size);
int ch;

do {
System.out.println("\nEnter~\n1. To push\n2. To pop\n3. To get peek element\n4. To display\n0. To Exit");
System.out.print("Enter your Choice: ");
ch = sc.nextInt();

switch (ch) {
case 1:
try {
System.out.print("Enter the element: ");
stkObj.push(sc.nextInt());
} catch (StackException e) {
System.err.println("Exception Caught: " + e);
}
break;

case 2:
try {
System.out.println("Popped element: " + stkObj.pop());
} catch (StackException e) {
System.err.println("Exception Caught: " + e);
}
break;

case 3:
stkObj.peek();
break;
case 4:
stkObj.display();
break;
case 0:
break;
default:
System.out.println("Invalid Choice!");
}
} while (ch != 0);

}
}

You might also like