Phihh
Phihh

Reputation: 13

How to print the first 10 lines from an enhanced for loop

I have a file with over 1000 names it also include the sex and how many people have the name.

example

Sarah F 2000

I am trying to print the first 10 lines that was created from my for loop, but for some reason what i tried is only printing the last line 10 times.

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;

OneName file

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);

}
}

OneNameCount

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; 
 }
}
}

Main Program

import java.io.*;
import java.util.*;

public class TopNames
{
public static void main(String args[])
{
    String line = ""; // string var to hold entire line

if (args.length < 1)
    {
    System.out.println("\nYou forgot to put a Year on the command line.");
    System.exit(1);
    };
String inFile = args[0];  // file name off command line
String year = inFile;
NameYear list = new NameYear(year);

}


}

Upvotes: 0

Views: 1169

Answers (2)

Marco Mercuri
Marco Mercuri

Reputation: 1127

Your error is here:

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;
}

First of all in your for loop you are not using the i variable that is your count indicator. This means that the descending() method has no any awareness of i, how he could return something different?

Try to modify descending() in something like this:

public String descending(int i) {
    String x = "";
    Collections.sort(oneName, new OneNameCountCompare());
    OneName b = oneName.get(i);

    x =  b.toString();

    return x;
}

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075567

Your descending function returns one string, and always the same string (the last one in the order after sorting the collection). It doesn't matter how often you call it, if the data doesn't change, you'll always get back that same, last, string.

If you want the first 10 after sorting, descending would need to return a List<String> containing those 10:

public List<String> descending()
{
    List<String> x = new ArrayList<String>(10);
    Collections.sort(oneName, new OneNameCountCompare());
    for(OneName b: oneName)
    {
        x.add(b.toString());
        if (x.size() == 10) // Or don't use enhanced for, use an index instead
        {
            break;
        }
    }
    return x;
}

Then when printing it, replace your for (int i = 0 ; i < 10; i++) loop with:

for (String s : descending())
{
    System.out.println(s);
}

Upvotes: 3

Related Questions