I am supposed to take input from a text file which looks like this:
rno year rank
22 2004 12
18 2004 17
43 2005 15
43 2006 45
18 2005 23
22 2005 15
43 2004 16
22 2006 20
I am supposed to sort these and produce the output in the following order:
rno 2004 2005 2006
18 17 23
22 12 15 20
43 16 15 45
If there is no rank available for the roll no. for the corresponding year then print a space
I was able to do this with the following code:
public class Test {
public static void main(String args[]) throws FileNotFoundException{
String[] rollNo=new String[20];
String[] year=new String[20];
String[] rank=new String[20];
int count=1;
int cnt=0;
Scanner scn=new Scanner(new File("D:/abc.txt"));
while(scn.hasNextLine()){
Scanner sc=new Scanner(scn.nextLine());
while(sc.hasNext()){
if(count==1){
rollNo[cnt]=sc.next();
count++;
}
else if(count==2){
year[cnt]=sc.next();
count++;
}
else{
rank[cnt]=sc.next();
count=count-2;
}
}
cnt++;
}
TreeSet<String> yr=new TreeSet<String>();
for(int i=1;i<year.length;i++)
if(year[i]!=null)
yr.add(year[i]);
TreeSet<String> rl=new TreeSet<String>();
for(int i=1;i<rollNo.length;i++)
if(rollNo[i]!=null)
rl.add(rollNo[i]);
Hashtable<String,String> y1=new Hashtable<String,String>();
for(int ct=0;ct<year.length;ct++)
if(year[ct]!=null)
if(year[ct].equals("2004"))
y1.put(rollNo[ct], rank[ct]);
Hashtable<String,String> y2=new Hashtable<String,String>();
for(int ct=0;ct<year.length;ct++)
if(year[ct]!=null)
if(year[ct].equals("2005"))
y2.put(rollNo[ct], rank[ct]);
Hashtable<String,String> y3=new Hashtable<String,String>();
for(int ct=0;ct<year.length;ct++)
if(year[ct]!=null)
if(year[ct].equals("2006"))
y3.put(rollNo[ct], rank[ct]);
System.out.print(rollNo[0]);
for(Object obj:yr)
System.out.print(" "+obj);
System.out.println();
for(Object obj:rl){
System.out.print(obj+" ");
if(y1.containsKey(obj))
System.out.print(y1.get(obj)+" ");
else
System.out.print(" ");
if(y2.containsKey(obj))
System.out.print(y2.get(obj)+" ");
else
System.out.print(" ");
if(y3.containsKey(obj))
System.out.print(y3.get(obj)+" ");
else
System.out.print(" ");
System.out.println();
}
}
}
But now the problem is that the hashtables for the years are hardcoded and I want to make this program dynamic meaning whatever the input (no of years, rank or roll no), I want my output in the same format for any input.
I did it.