Object Array Example In Java





import java.util.ArrayList;
import java.util.Scanner;


public class Main {

    public static void main(String[] args) {
        // TODO code application logic here
         Scanner input =new Scanner(System.in);
       
        String x,s;
        double y;
        int n,i,j,t;
      
        result[] a=new result[1000];
        result ob=new result();
        ob.get(a);
       
    }
   
   
}
class result {
    String x,s,st;
    double y,t;
    public int get(result[] a)
    {
        int n,i,j;
        Scanner input=new Scanner(System.in);
        n=input.nextInt();
        for(i=0;i<n;i++)
        {
           a[i]=new result();//object array should be initialized by constructor
           a[i].x= input.next();
          
           a[i].y=input.nextDouble();
          
        }
      
      
        for(i=0;i<n;i++)
        {
            for(j=i+1;j<n;j++)
            {
                if(a[i].y<a[j].y)
                {
                    t=a[i].y;
                    st=a[i].x;
                    a[i].y=a[j].y;
                    a[i].x=a[j].x;
                    a[j].y=t;
                    a[j].x=st;
                }
            }
        }
       
          //sort if same
        
        for(i=0;i<n;i++)
        {
            for(j=i+1;j<n;j++)
            {
                if(a[i].y==a[j].y)
                {
                    if(a[i].x.compareTo(a[j].x)>0)
                    {
                        s=a[i].x;
                        a[i].x=a[j].x;
                        a[j].x=s;
                    }
                       
                }
            }
        }
        double cg=0.0;
        int c=0;
        for(i=0;i<n;i++)
        {
            if(a[i].y>cg || a[i].y<cg)
            {
                c++;
            }
            cg=a[i].y;
            System.out.println(c+"."+a[i].x);
        }
          
        return 0;
    }
}



 
Input 

5
Ashadullah 3.20
Aaashish 3.90
Aaabbas 3.80
Aaaanish 3.80
Shawon 3.16


Output

1.Aaashish
2.Aaaanish
2.Aaabbas
3.Ashadullah
4.Shawon

Download Coding Interview Book and Get More Tutorials for Coding and Interview Solution: Click Here

Download System Design Interview Book and Get More Tutorials and Interview Solution: Click Here

Do you need more Guidance or Help? Then Book 1:1 Quick Call with Me: Click Here

Share on Google Plus

About Ashadullah Shawon

I am Ashadullah Shawon. I am a Software Engineer. I studied Computer Science and Engineering (CSE) at RUET. I Like To Share Knowledge. Learn More: Click Here
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment