/*
Write java programs that include generic
method to satisfy the following property.
To counts the number of odd integers in an
integer list
To exchange the positions of two different
elements in an array.
To find the maximal element in the range
[begin, end] of a list.
*/
// Generic programming
import java.util.*;
class Gen<T1 extends Number>
{
int
max;
T1
[] Arr;
Scanner
s = new Scanner(System.in);
Gen(T1
[] A)
{
Arr
= A;
}
public
void fnOdd()
{
int
oddcount = 0;
for(int
i = 0;i<Arr.length;i++)
{
int
x = (int)(Arr[i].doubleValue());
if(x%2==1)
oddcount++;
}
System.out.println("Number
of odd elements = "+oddcount);
}
public
void fnExchange()
{
System.out.print("\nEnter
position 1 : ");
int
pos1 = s.nextInt();
System.out.print("\nEnter
position 2 : ");
int
pos2 = s.nextInt();
if(pos1<Arr.length
&& pos2<Arr.length)
{
System.out.println("Array
elements before exchange : ");
for(int
i = 0;i<Arr.length;i++)
System.out.print(Arr[i]+"\t");
T1
tmp = Arr[pos1];
Arr[pos1]
= Arr[pos2];
Arr[pos2]
= tmp;
System.out.println("\nArray
elements after exchange : ");
for(int
i = 0;i<Arr.length;i++)
System.out.print(Arr[i]+"\t");
}
else
System.out.println("Invalid
positions.");
}
public
void fnMax()
{
System.out.print("\nEnter
starting position : ");
int
pos1 = s.nextInt();
System.out.print("\nEnter
ending position : ");
int
pos2 = s.nextInt();
if(pos1<Arr.length
&& pos2<Arr.length && pos1<pos2)
{
max
= (int)Arr[pos1].doubleValue();
for(int
i = pos1+1;i<pos2;i++)
if((int)Arr[i].doubleValue()
> max )
max
= (int)Arr[i].doubleValue();
System.out.println("\nMaximum
element = "+max);
}
else
System.out.println("Invalid
positions.");
}
}
public class GP1
{
public
static void main(String as[])
{
Integer
[] IntArr = {2,4,1,6,5,3,7};
Gen<Integer>
g1 = new Gen<Integer>(IntArr);
g1.fnOdd();
g1.fnExchange();
g1.fnMax();
}
}
No comments:
Post a Comment
Don't be a silent reader...
Leave your comments...
Anu