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

Java

Uploaded by

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

Java

Uploaded by

shubhmishra8508
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

/*1) Write a java program to take input as a command line argument.

Your name, course, university rollno and


semester. Display the information as.
Name:
UniversityRollNo:
Course:
Semester:*/
public class D {
public static void main(String[] args) {
System.out.println("Name- Aadarsh Negi, Sec- D, Class_Roll_num-57,
University_Roll_num=2016551");
String name = args[0];
int roll = Integer.parseInt(args[1]);
String course = args[2];
int sem = Integer.parseInt(args[3]);
System.out.println("name - " + name);
System.out.println("roll_no - " + roll);
System.out.println("course - " + course);
System.out.println("semester - " + sem);
}
}

/*2) Using the switch statement, write a menu-driven program to calculate the maturity amount of a bank deposit.
The user is given the following options:
(i) Term Deposit
(ii) Recurring Deposit
For option (i) accept Principal (p), rate of interest (r) and time period in years (n). Calculate and outpute the maturity
amount (a) receivable using the formula a = p[1 + r / 100]n.
For option (ii) accept monthly installment (p), rate of interest (r) and time period in months (n). Calculate and output
the maturity amount (a) receivable using the formula a = p * n + p * n(n + 1) / 2 * r / 100 * 1 / 12.*/

import java.util.*;

public class D {
public static void main(String args[]) {
System.out.println("Name- Aadarsh Negi, Sec- D, Class_Roll_num-57,
University_Roll_num=2016551");
Scanner in = new Scanner(System.in);
System.out.println("1. for Term Deposit");
System.out.println("2. for Recurring Deposit");
System.out.print("Enter your choice: ");
int ch = in.nextInt();
double p = 0.0, r = 0.0, a = 0.0;
int n = 0;
switch (ch) {
case 1:
System.out.print("Enter Principal: ");
p = in.nextDouble();
System.out.print("Enter Interest Rate: ");
r = in.nextDouble();
System.out.print("Enter time in years: ");
n = in.nextInt();
a = p * Math.pow(1 + r / 100, n);
System.out.println("Maturity amount = " + a);
break;
case 2:
System.out.print("Enter Monthly Installment: ");
p = in.nextDouble();
System.out.print("Enter Interest Rate: ");
r = in.nextDouble();
System.out.print("Enter time in months: ");
n = in.nextInt();
a = p * n + p * ((n * (n + 1)) / 2) * (r / 100) * (1 / 12.0);
System.out.println("Maturity amount = " + a);
break;
default:
System.out.println("Invalid choice");
}
}
}

/*3) Write a Program to find if the given numbers are Friendly pair or not (Amicable or not). Friendly Pair are two or
more numbers with a common abundance.*/
import java.util.*;
public class D{
static int getSum(int n){
int res=0;
for(int i=1;i*i<=n;i++){
if(n%i==0){
res+=i;
if(i!=n/i) res+=n/i;
}
}
return res;
}
public static void main(String[] args){
System.out.println("Name- Aadarsh Negi, Sec- D, Class_Roll_num-57, University_Roll_num=2016551");
Scanner in = new Scanner(System.in);
System.out.print("enter the value of n and m :- ");

int n = in.nextInt();
int m = in.nextInt();

int sumN = getSum(n);


int sumM = getSum(m);

if(sumN/n == sumM/m) System.out.print("friendly pair");


else System.out.print("not a friendly pair");
}
}

/*4) Write a Program to replace all 0's with 1 in a given integer. Given an integer as an input, all the 0's in the
number has to be replaced with 1.*/
import java.util.*;
public class D{
static int replace(int n){
int res=0;
int f=1;
while(n>0){
int last = n%10;
last = Math.max(1,last);
last*=f;
res+=last;
n/=10;
f*=10;
}
return res;
}
public static void main(String[] args){
System.out.println("Name- Aadarsh Negi, Sec- D, Class_Roll_num-57, University_Roll_num=2016551");
Scanner in = new Scanner(System.in);
System.out.print("enter the value of n:- ");
int n = in.nextInt();
int res = replace(n);
System.out.print("new number:- "+ res);
}
}

/*5) Write a Program for Printing an array into Zigzag fashion. Suppose you were given an array of integers, and you
are told to sort the integers in a zigzag pattern. In general, in a zigzag pattern, the first integer is less than the second
integer, which is greater than the third integer, which is less than the fourth integer, and so on. Hence, the
converted array should be in the form of e1 < e2 > e3 < e4 > e5 < e6.*/
import java.util.*;
public class D {
public static void swap(int a[]) {
boolean flag = true; int temp=0;
for(int i=0;i<a.length-2;i++) {
if(flag) {
if(a[i]>a[i+1]) {
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
} else {
if(a[i]<a[i+1]) {
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}}
flag^=true;
}}
public static void main(String args[]){
System.out.println("Name- Aadarsh Negi, Sec- D, Class_Roll_num-57, University_Roll_num=2016551");
Scanner in = new Scanner(System.in);
System.out.print("Enter n: ");
int n = in.nextInt();
int a[] = new int[n];
System.out.print("Enter elements in array: ");
for(int i=0;i<n;i++) a[i]=in.nextInt();
swap(a);
System.out.print("Zigzag Array: ");
System.out.println(Arrays.toString(a));
}}

/*6) Write a Program to rearrange positive and negative numbers in an array .*/
import java.util.*;
public class D {
public static void main(String args[]){
System.out.println("Name- Aadarsh Negi, Sec- D, Class_Roll_num-57, University_Roll_num=2016551");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int a[] = new int[n];
for(int i=0;i<n;i++) a[i]=in.nextInt();
int last=0;
int cur=0;
while(cur<n) {
if(a[cur]<0 && last<cur) {
int temp = a[cur];
a[cur] = a[last];
a[last] = temp;
last++;
}else cur++;
}
for(int i=0;i<n;i++)
System.out.print(a[i]+" ");
}}

/*7) Program to find the saddle point coordinates in a given matrix. A saddle point is an element of the matrix, which
is the minimum element in its row and the maximum in its column.*/
import java.util.*;
public class D {
public static void main(String args[]){
System.out.println("Name- Aadarsh Negi, Sec- D, Class_Roll_num-57, University_Roll_num=2016551");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int ar[][] = new int[n][m];
for(int i=0;i<n;i++) for(int j=0;j<m;j++) ar[i][j]=in.nextInt();
int x,y,elem;
x=y=elem=-1;
for(int i=0;i<n;i++) for(int j=0;j<m;j++){
int mn = ar[i][j];
int mx = ar[i][j];

for(int k=0;k<m;k++) mn = (mn>ar[i][k]?ar[i][k]:mn);


for(int k=0;k<n;k++) mx = (mx<ar[k][j]?ar[k][j]:mx);

if(mn==mx && mn==ar[i][0]) {


x=i;
y=j;
elem = mn;
break;
}}
if(x==-1) System.out.print("No Saddle point");
else System.out.print("Saddle point (" + x +", "+y+") :"+elem);
}}

/*8) Program to find all the patterns of 0(1+)0 in the given string. Given a string containing 0's and 1's, find the total
number of 0(1+)0 patterns in the string and output it.
0(1+)0 - There should be at least one '1' between the two 0's.
*/
import java.util.*;
public class D {
public static void main(String args[]){
System.out.println("Name- Aadarsh Negi, Sec- D, Class_Roll_num-57,
University_Roll_num=2016551");
Scanner in = new Scanner(System.in);
String s;
s = in.next();
int prev = -1;
int cnt=0;
for(int i=0;i< s.length();i++) {
char c = s.charAt(i);
if(c=='0') {
if(prev!=-1 && i-prev-1>0) cnt++;
prev=i;
}
}
System.out.print("Count - " + cnt);
}}

/*9) Write a java program to delete vowels from given string using StringBuffer class.*/
import java.util.*;
public class D {
public static void main(String[] args) {
System.out.println("Name- Aadarsh Negi, Sec- D, Class_Roll_num-57,
University_Roll_num=2016551");
Scanner in = new Scanner(System.in);
String s = in.next();
String s1 = "";
s1 = s.replaceAll("[aeiou]", "");
System.out.println("String after removing vowel : "+s1);
}
}

/*10) Write a java program to create a class named 'Bank ' with the following data members:
Name of depositor
Address of depositor
Account Number
Balance in account
Class 'Bank' has a method for each of the following:
1 - Generate a unique account number for each depositor
For first depositor, account number will be 1001, for second depositor it will be 1002 and so on
2 - Display information and balance of depositor
3 - Deposit more amount in balance of any depositor
4 - Withdraw some amount from balance deposited
5 - Change address of depositor

After creating the class, do the following operations


1 - Enter the information (name, address, account number, balance) of the depositors. Number of depositors is to be
entered by user.
2 - Print the information of any depositor.
3 - Add some amount to the account of any depositor and then display final information of that depositor
4 - Remove some amount from the account of any depositor and then display final information of that depositor
5 - Change the address of any depositor and then display the final information of that depositor
6 - Randomly repeat these processes for some other bank accounts.*/

import java.util.Scanner;
class BankDetails {
private String accno;
private String name;
private String address;
private long balance;
Scanner sc = new Scanner(System.in);

public void openAccount() {


System.out.print("Enter Account No: ");
accno = sc.next();
System.out.print("Enter Address: ");
address = sc.next();
System.out.print("Enter Name: ");
name = sc.next();
System.out.print("Enter Balance: ");
balance = sc.nextLong();
}

public void showAccount() {


System.out.println("Name of account holder: " + name);
System.out.println("Account no.: " + accno);
System.out.println("address: " + address);
System.out.println("Balance: " + balance);
}

public void deposit() {


long amt;
System.out.println("Enter the amount you want to deposit: ");
amt = sc.nextLong();
balance = balance + amt;
}

public void changeadd() {


System.out.print("Enter New Address: ");
address = sc.next();
}

public void withdrawal() {


long amt;
System.out.println("Enter the amount you want to withdraw: ");
amt = sc.nextLong();
if (balance >= amt) {
balance = balance - amt;
System.out.println("Balance after withdrawal: " + balance);
} else {
System.out.println("Your balance is less than " + amt + "\tTransaction failed...!!" );
}
}

public boolean search(String ac_no) {


if (accno.equals(ac_no)) {
showAccount();
return (true);
}
return (false);
}
}
public class D {
public static void main(String arg[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Name- Aadarsh Negi, Sec- D, Class_Roll_num-57, University_Roll_num=2016551");
System.out.print("How many number of customers do you want to input? ");
int n = sc.nextInt();
BankDetails C[] = new BankDetails[n];
for (int i = 0; i < C.length; i++) {
C[i] = new BankDetails();
C[i].openAccount();
}

int ch;
do {
System.out.println("\n ***Banking System Application***");
System.out.println("1. Display all account details \n 2. Search by Account number\n 3. Deposit the amount \n
4. Withdraw the amount \n 5.change address \n 6.exit ");
System.out.println("Enter your choice: ");
ch = sc.nextInt();
switch (ch) {
case 1:
for (int i = 0; i < C.length; i++) {
C[i].showAccount();
}
break;
case 2:
System.out.print("Enter account no. you want to search: ");
String ac_no = sc.next();
boolean found = false;
for (int i = 0; i < C.length; i++) {
found = C[i].search(ac_no);
if (found) {
break;
}
}
if (!found) {
System.out.println("Search failed! Account doesn't exist..!!");
}
break;
case 3:
System.out.print("Enter Account no. : ");
ac_no = sc.next();
found = false;
for (int i = 0; i < C.length; i++) {
found = C[i].search(ac_no);
if (found) {
C[i].deposit();
break;
}
}
if (!found) {
System.out.println("Search failed! Account doesn't exist..!!");
}
break;
case 4:
System.out.print("Enter Account No : ");
ac_no = sc.next();
found = false;
for (int i = 0; i < C.length; i++) {
found = C[i].search(ac_no);
if (found) {
C[i].withdrawal();
break;
}
}
if (!found) {
System.out.println("Search failed! Account doesn't exist..!!");
}
break;
case 5:
System.out.print("Enter Account no. : ");
ac_no = sc.next();
found = false;
for (int i = 0; i < C.length; i++) {
found = C[i].search(ac_no);
if (found) {
C[i].changeadd();
break;
}
}
if (!found) {
System.out.println("Search failed! Account doesn't exist..!!");
}
break;
case 6:
System.out.println("See you soon...");
break;
}
}
while (ch != 5);
}
}

/*11) Define a class WordExample having the following description:


Data members/instance variables:
private String strdata : to store a sentence.*/
import java.util.*;

class D {
private String strdata;

D(String x) {
x = x.trim().toUpperCase();
int len = x.length();
char last = x.charAt(len - 1);
if (last != '!' && last != '.' && last != '?') {
System.out.print("Invalid Input.");
return;
}
strdata = x;
}

public static boolean isVowel(char ch) {


ch = Character.toUpperCase(ch);
boolean ret = false;
if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')
ret = true;
return ret;
}

public static void main(String args[]) {


System.out.println("Name- Aadarsh Negi, Sec- D, Class_Roll_num-57,
University_Roll_num=2016551");
Scanner sc = new Scanner(System.in);
System.out.print("Enter a sentence:");
String x = sc.nextLine();
D w = new D(x);
StringTokenizer st = new StringTokenizer(x);
StringBuffer vowel = new StringBuffer();
StringBuffer cons = new StringBuffer();
int c = 0;
while (st.hasMoreTokens()) {
String word = st.nextToken();
int len = word.length();
if (isVowel(word.charAt(0)) && isVowel(word.charAt(len - 1))) {
vowel.append(word);
vowel.append(" ");
c++;
} else {
cons.append(word);
cons.append(" ");
}
}
String newStr = vowel.toString() + cons.toString();
System.out.println("Number of words beginning and ending with vowels are:" + c);
System.out.println("New string is:" + newStr);
}
}

/*12) Write a Java program to create a class called ArrayDemo and overload arrayFunc() function.
void arrayFunc(int [], int) To find all pairs of elements in an Array whose sum is equal to a given number :*/
class ArrayFunc {
void arrayFunc(int arr[], int target) {
for (int i = 0; i < arr.length; i++) {
for (int j = i; j < arr.length; j++)
if (arr[i] + arr[j] == target)
System.out.print("{" + arr[i] + ", " + arr[j] + "} ");
}
}
void arrayFunc(int a[], int b[], int p, int q) {
int ans[] = new int[p + q];
int i = 0, j = 0, k = 0;
while (i < p && j < q) {
if (a[i] <= b[j]) {
ans[k++] = a[i++];
} else {
ans[k++] = b[j++];
}
}
while (i < p)
ans[k++] = a[i++];
while (j < q)
ans[k++] = b[j++];
System.out.print("\nIn merged sorted order : ");
for (int it : ans)
System.out.print(it + " ");
}
}
public class D {
public static void main(String args[]) {
System.out.println("Name- Aadarsh Negi, Sec- D, Class_Roll_num-57,
University_Roll_num=2016551");
int a[] = { 1, 2, 4, 5, 7, 8 };
int b[] = { 3, 6, 9, 10 };
int p = a.length, q = b.length;
int target = 6;
ArrayFunc obj = new ArrayFunc();
obj.arrayFunc(a, target);
obj.arrayFunc(a, b, p, q);
}}

/*13) Write a java program to calculate the area of a rectangle, a square and a circle. Create an abstract class
'Shape' with three abstract methods namely rectangleArea() taking two parameters, squareArea() and circleArea()
taking one parameter each.
Now create another class ‘Area’ containing all the three methods rectangleArea(),squareArea() and circleArea() for
printing the area of rectangle, square and circle respectively. Create an object of class Area and call all the three
methods.*/
import java.util.*;
public class D {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter length,breadth,side,radius\n");
int l = sc.nextInt();
int b = sc.nextInt();
int s = sc.nextInt();
int r = sc.nextInt();
Area a = new Area(l, b, s, r);
System.out.println("Area of Rectangle: " + a.rectangleArea());
System.out.println("Area of Square: " + a.squareArea());
System.out.println("Area of Circle: " + a.circleArea());
}
}
abstract class Shape {
int l, b, s, r;
Shape(int l, int b, int s, int r) {
this.l = l;
this.b = b;
this.s = s;
this.r = r;
}
protected abstract int rectangleArea();
protected abstract int squareArea();
protected abstract double circleArea();
}

class Area extends Shape {


Area(int l, int b, int s, int r) {
super(l, b, s, r);
}
public int rectangleArea() {
return l * b;
}
public int squareArea() {
return s * s;
}
public double circleArea() {
return 3.14 * (double) r * (double) r;
}
}
/*14) Write a java program to implement abstract class and abstract method with following details:*/
public class D {
public static void main(String[] args) {
System.out.println("Name- Aadarsh Negi, Sec- D, Class_Roll_num-57,
University_Roll_num=2016551");
Fahrenheit f = new Fahrenheit();
Celsius c = new Celsius();
f.setTempData(51.4);
f.changeTemp();
c.setTempData(70.3);
c.changeTemp();
}
}

abstract class Temperature {


protected double temp;
public void setTempData(double temp) {
this.temp = temp;
}
protected abstract void changeTemp();
}

class Fahrenheit extends Temperature {


Fahrenheit() {}

private double ctemp;


public void changeTemp() {
ctemp = (5.0 / 9.0) * (temp - 32);
System.out.println("Temperature in Celsius: " + ctemp);
}
}
class Celsius extends Temperature {
Celsius() {}
private double ftemp;
public void changeTemp() {
ftemp = (9.0 / 5.0) * temp + 32;
System.out.println("Temperature in Fahrenheit: " + ftemp);
}
}

/*15) Write a java program to create an interface that consists of a method to display volume () as an abstract
method and redefine this method in the derived classes to suit their requirements.
Create classes called Cone, Hemisphere and Cylinder that implements the interface. Using these three classes, design
a program that will accept dimensions of a cone, cylinder and hemisphere interactively and display the volumes.*/
import java.util.*;
public class D {
public static void main(String[] args) {
System.out.println("Name- Aadarsh Negi, Sec- D, Class_Roll_num-57,
University_Roll_num=2016551");
Scanner sc= new Scanner(System.in);
double r,h;
System.out.println("Enter radius and height of cone: ");
r=sc.nextDouble();
h=sc.nextDouble();
Cone c = new Cone(r, h);
c.volume();
System.out.println("Enter radius of hemisphere: ");
r=sc.nextDouble();
Hemisphere hem = new Hemisphere(r);
hem.volume();
System.out.println("Enter radius and height of cylinder: ");
r=sc.nextDouble();
h=sc.nextDouble();
Cylinder cy = new Cylinder(r, h);
cy.volume();
sc.close();
}
}
interface Cal_Volume{
public abstract void volume();
}
class Cone implements Cal_Volume{
private double r,h;
Cone(double r, double h){
this.r=r;
this.h=h;
}
public void volume(){
System.out.println("Volume of Cone: "+(1.0/3.0)*3.14*r*r*h);
}
}
class Hemisphere implements Cal_Volume{
private double r;
Hemisphere(double r){
this.r=r;
}
public void volume(){
System.out.println("Volume of Hemisphere: "+(2.0/3.0)*3.14*r*r*r);
}
}
class Cylinder implements Cal_Volume{
private double r,h;
Cylinder(double r, double h){
this.r=r;
this.h=h;
}
public void volume(){
System.out.println("Volume of Cylinder: "+3.14*r*r*h);
}
}
/*16) Write a java program to accept and print the employee details during runtime. The details will include
employee id, name, dept_ Id. The program should raise an exception if user inputs incomplete or incorrect data. The
entered value should meet the following conditions:
(i) First Letter of employee name should be in capital letter.
(ii) Employee id should be between 2001 and 5001
(iii) Department id should be an integer between 1 and 5.
If the above conditions are not met then the application should raise specific exception else should complete normal
execution.*/
import java.util.*;

class mycustomclass extends Exception {


public mycustomclass(String str) {
super(str);
}
}

public class D {
public static void main(String[] args) {
System.out.println("Name- Aadarsh Negi, Sec- D, Class_Roll_num-57,
University_Roll_num=2016551");
Scanner sc = new Scanner(System.in);
try {
System.out.println("Enter the employee name: ");
String name = sc.next();
char c = name.charAt(0);
if (Character.isLowerCase(c)) {
throw new mycustomclass("First letter of the name is not inuppercase.");
}

System.out.println("Enter the employee ID: ");


int emp_id = sc.nextInt();
if (emp_id < 2001 || emp_id > 5001) {
throw new mycustomclass("Employee ID is not between 2001 and 5001.");
}

System.out.println("Enter the department ID: ");


int dept_id = sc.nextInt();
if (dept_id < 1 || dept_id > 5) {
throw new mycustomclass("Department ID is not between 1 and 5.");
}
System.out.println("Name of employee :" + name);
System.out.println("Employee ID :" + emp_id);
System.out.println("Department ID :" + dept_id);
} catch (Exception e) {
System.out.println("Exception occured! " + e.getMessage());
}
}
}

/*17) Create a class MyCalculator which consists of a single method power(int, int).
This method takes two integers, n and p, as parameters and finds np .
If either n or p is negative, then the method must throw an exception which says "n and p should be non-
negative".*/
import java.util.Scanner;

class MyCalculator {
public int power(int n, int p) throws Exception {
if (n < 0 || p < 0) {
throw new Exception("n or p should not be negative.");
} else if (n == 0 && p == 0) {
throw new Exception("n and p should not be zero.");
} else {
return (int) Math.pow(n, p);
}
}
}

public class D {
public static final MyCalculator my_calculator = new MyCalculator();
public static final Scanner in = new Scanner(System.in);

public static void main(String[] args) {


System.out.println("Name- Aadarsh Negi, Sec- D, Class_Roll_num-57,
University_Roll_num=2016551");
while (in.hasNextInt()) {
int n = in.nextInt();
int p = in.nextInt();
try {
System.out.println(my_calculator.power(n, p));
} catch (Exception e) {
System.out.println(e);
}
}
}
}

/*18) Write a java file handling program to count and display the number of palindrome present in a text file
"myfile.txt".*/
import java.util.*;
import java.io.*;

public class D {
public static boolean ispalindrome(String s) {
int low, high;
low = 0;
high = s.length() - 1;
while (low < high) {
if (s.charAt(low) != s.charAt(high)) {
return false;
}
low++;
high--;
}
return true;
}
public static void main(String[] args) {
System.out.println("Name- Aadarsh Negi, Sec- D, Class_Roll_num-57,
University_Roll_num=2016551");
try {
File f1 = new File("C:\\Users\\ad\\eclipse-workspace\\JavaLab\\src\\myfile.txt");
Scanner s = new Scanner(f1);
int c = 0;
System.out.print("File content -");
while (s.hasNext()) {
String word = s.next();
System.out.print(" "+word);
if (ispalindrome(word))
c++;
}
s.close();
System.out.print("\n"+c);
} catch (FileNotFoundException e) {
System.out.println("An error has occurred.");
e.printStackTrace();
}
}
}

/*20) Write a java program for to solve producer consumer problem in which a producer produce a value and
consumer consume the value before producer generate the next value.*/
import java.util.LinkedList;

public class D {
public static void main(String[] args) throws Exception
{
System.out.println("Name- Aadarsh Negi, Sec- D, Class_Roll_num-57,
University_Roll_num=2016551");
final PC pc = new PC();
Thread t1 = new Thread(new Runnable() {
@Override
public void run()
{
try {
pc.produce();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run()
{
try {
pc.consume();
}
catch (Exception e) {
e.printStackTrace();
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
}
public static class PC {
LinkedList<Integer> list = new LinkedList<>();
int capacity = 2;
public void produce() throws InterruptedException
{
int value = 0;
while (true) {
synchronized (this)
{
while (list.size() == capacity)
wait();
System.out.println("Producer produced-"+ value);
list.add(value++);
notify();
Thread.sleep(1000);
}
}
}
public void consume() throws InterruptedException
{
while (true) {
synchronized (this)
{
while (list.size() == 0)
wait();
int val = list.removeFirst();
System.out.println("Consumer consumed-"+ val);
notify();
Thread.sleep(1000);
}
}
}
}
}

/*21) Write a method removeEvenLength that takes an ArrayList of Strings as a parameter and that removes all of
the strings of even length from the list.*/
import java.util.*;
public class D{
public static void removeEvenLength(ArrayList<String> s ) {
Iterator<String> iterator = s.iterator();
while( iterator.hasNext() ) {
final String word = iterator.next();
if( word.length() % 2 == 0 ) {
iterator.remove();
}
}
}
public static void main(String args[]) {
System.out.println("Name- Aadarsh Negi, Sec- D, Class_Roll_num-57,
University_Roll_num=2016551");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
ArrayList<String> ss = new ArrayList<String>();
for(int i=0;i<n;i++) {
String temp = in.next();
ss.add(temp);
}
removeEvenLength(ss);
for(String i:ss) System.out.print(i+" ");
}
}

/*22) Write a method swapPairs that switches the order of values in an ArrayList of Strings in a pairwise fashion.
Your method should switch the order of the first two values, then switch the order of the next two, switch the order
of the next two, and so on.*/
import java.util.*;
public class D{
public static void main(String args[]) {
System.out.println("Name- Aadarsh Negi, Sec- D, Class_Roll_num-57,
University_Roll_num=2016551");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
ArrayList<String> s = new ArrayList<String>();
for(int i=0;i<n;i++) {
String temp = in.next();
s.add(temp);
}
for(int i=0;i<s.size();i+=2)
Collections.swap(s, i, i+1);
for(String i:s) System.out.print(i+" ");
}
}

/*
* 23) Write a method called alternate that accepts two Lists of integers as its
* parameters and returns a new List containing alternating elements from the
* two lists, in the following order: • First element from first list • First
* element from second list • Second element from first list • Second element
* from second list • Third element from first list • Third element from second
* list • … If the lists do not contain the same number of elements, the
* remaining elements from the longer list should be placed consecutively at the
* end. For example, for a first list of (1, 2, 3, 4, 5) and a second list of
* (6, 7, 8, 9, 10, 11, 12), a call of alternate(list1, list2) should return a
* list containing (1, 6, 2, 7, 3, 8, 4, 9, 5, 10, 11, 12). Do not modify the
* parameter lists passed in.
*/
import java.util.*;
public class D{
public static ArrayList<Integer> Alt(ArrayList<Integer> a,ArrayList<Integer> b) {
ArrayList<Integer> res = new ArrayList<Integer>();
int i=0;
int j=0;

while(i<a.size() && j<b.size()) {


int x = a.get(i);
int y = b.get(j);
res.add(x);
res.add(y);
i++;
j++;
}
while(i<a.size()) {
int x = a.get(i);
res.add(x);
i++;
}
while(j<b.size()) {
int x = b.get(j);
res.add(x);
j++;
}
return res;
}
public static void main(String args[]) {
System.out.println("Name- Aadarsh Negi, Sec- D, Class_Roll_num-57,
University_Roll_num=2016551");
Scanner in = new Scanner(System.in);
ArrayList<Integer> a = new ArrayList<Integer>();
ArrayList<Integer> b = new ArrayList<Integer>();
int n=in.nextInt();
for(int i=0;i<n;i++) {
int temp = in.nextInt();
a.add(temp);
}
int m=in.nextInt();
for(int i=0;i<m;i++) {
int temp = in.nextInt();
b.add(temp);
}
ArrayList<Integer> res = Alt(a,b);
for(int i:res) System.out.print(i+" ");
}
}

You might also like