Title: How to print the first 10 lines from an enhanced for loop
Tags: java;class;for-loop
Question: 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&gt; oneName = new ArrayList<OneName&gt;();
public NameYear(String year)
String line = "";
String Top = "";
Scanner sc = null;
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&gt;
public int compare(OneName b1, OneName b2)
if(b1.getCount() <b2.getCount())
return 1;
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);
Comment: Walk through the code with a debugger and watch what happens. In particular, pay attention to what you're returning from `descending`.

Comment: to print what is in the descending function

Comment: This is too much code for a question about printing some items in a loop. Try and create a smaller example that demonstrates your problem.

Comment: Firstly throw Illegal argument exception and not NPE in OneName#setName.
Secondly why are you sorting it ? Just display it as you want to see first 10 that you entered.

Comment: looks like your descending method is going through your list and setting each object.toString to x. The problem is you're looping through the whole list and always getting the final object's value.toString = x, so the last object is being printed 10 times

Comment: Your code is a mess. What is the reason of this - System.out.println(descending()); ?

Here is the accepted answer: 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&gt; containing those 10:
public List<String&gt; descending()
List<String&gt; x = new ArrayList<String&gt;(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);
Comment for this answer: returning x gives me an incompatible type
Comment for this answer: and also the for loop to print is giving an not applicable to expression type
for (String s : descending())
Comment for this answer: did you change the method's return type to List? ... public List descending()

Here is another answer: 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;

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 6, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2014:00:10/02/14', 'FavoriteCount': 0.0, 'PostTypeId': 1, 'Tags': '<java><class><for-loop>', 'Title': 'How to print the first 10 lines from an enhanced for loop', 'ViewCount': 935, 'id': 26160725, 'user_AboutMe': None, 'user_AccountId': 5115885.0, 'user_DisplayName': 'Phihh', 'user_Reputation': 13.0, 'user_Views': 6.0, 'user_id': 4101020.0}}