Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.io.*;
- import java.util.Collections;
- public class NameYear
- {
- private String year;
- ArrayList<OneName> oneName = new ArrayList<OneName>();
- public NameYear(String year)
- {
- String line = "";
- String Top = "";
- Scanner sc = null;
- try
- {
- sc = new Scanner(new File
- ("/home/mathcs/courses/cs225/koch/names/yob"+year+".txt"));
- }
- catch (Exception e)
- {
- System.out.println("Error Year should be between 1880 and 2013 not "+ year);
- System.exit(1);
- }
- while(sc.hasNextLine())
- {
- // read a line from the input file via sc into line
- line = sc.nextLine();
- StringTokenizer stk = new StringTokenizer(line, ",");
- String name = stk.nextToken();
- char sex = stk.nextToken().charAt(0);
- int count = Integer.parseInt(stk.nextToken());
- OneName list = new OneName(name, sex, count);
- oneName.add(list);
- }
- for (int i = 0 ; i < 10; i++)
- {
- System.out.println(descending());
- }
- public String descending()
- {
- String x = "";
- Collections.sort(oneName, new OneNameCountCompare());
- for(OneName b: oneName)
- {
- x = b.toString();
- }
- return x;
- public class OneName
- {
- private String Name;
- private char Sex;
- private int Count;
- public OneName(String name, char sex, int count)
- {
- Name = name;
- Sex = sex;
- Count = count;
- }
- public String getName()
- {
- return Name;
- }
- public char getSex()
- {
- return Sex;
- }
- public int getCount()
- {
- return Count;
- }
- public void setName(String name)
- {
- if (name.length() < 1)
- {
- throw new NullPointerException("Baby name is missing");
- }
- Name = name;
- }
- private char M;
- private char F;
- public void setSex(char sex)
- {
- if( sex != M)
- {
- if(sex != F)
- {
- throw new IllegalArgumentException("Sex has to be M or F");
- }
- }
- Sex = sex;
- }
- public void setCount(int count)
- {
- if(count < 0)
- {
- throw new IllegalArgumentException("Count cant be negative");
- }
- Count = count;
- }
- public String toString()
- {
- return String.format("%s %c %d", Name, Sex, Count);
- }
- }
- import java.util.Comparator;
- import java.util.Collections;
- public class OneNameCountCompare implements Comparator<OneName>
- {
- public int compare(OneName b1, OneName b2)
- {
- if(b1.getCount() <b2.getCount())
- {
- return 1;
- }
- else
- {
- return -1;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement