Java
Slip28
Q.1) Write a java program to read n Students names from user, store them into the ArrayList collection. The program should not allow duplicate names. Display the names in Ascending order. [Marks 30]
Solution
import java.util.*;
import java.io.*;
class Ascending1
{
public static void main(String ar[]) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nEnter No Of Elements To Be Added:: ");
int no = Integer.parseInt(br.readLine());
ArrayList<String> a = new ArrayList<String>();
for(int i = 0; i<no; i++)
{
System.out.print("\nEnter First Name: ");
String str = br.readLine();
if(a.contains(str))
{
System.out.println("\nDuplicate Value Not Allowed");
i--;
}
else a.add(str);
}
Iterator<String> it = a.iterator();
System.out.println("Elements Present In The ArrayList = ");
while(it.hasNext())
{
System.out.println("\t"+ it.next());
}
Object o[] = a.toArray();
String obj[] = new String[o.length];
for(int i=0;i<o.length ; i++)
obj[i] = (String)o[i];
for(int i=0;i<obj.length -1; i++)
{
for(int j=0;j<obj.length -1 ; j++)
if(obj[j].compareTo(obj[j+1]) > 0)
{
String temp = obj[j];
obj[j] = obj[j+1];
obj[j+1] = temp;
}
}
for(int i=0; i < obj.length ; i++)
System.out.println(obj[i]);
}
}
Tags:
java