如何从增强的for循环中打印前10行

时间:2014-10-02 12:22:53

标签: java class for-loop

我有一个超过1000个名字的文件,它还包括性别和有多少人有这个名字。

例如

Sarah F 2000

我正在尝试打印从for循环创建的前10行,但出于某种原因,我尝试的只是打印最后一行10次。

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文件

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

主程序

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

}


}

2 个答案:

答案 0 :(得分:3)

您的descending函数返回一个字符串,并且始终使用相同的字符串(排序集合后的最后一个字符串)。你调用它的频率并不重要,如果数据没有变化,你总会得到同样的,最后一个字符串。

如果您想要排序后的前10个,descending需要返回包含10个的List<String>

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

然后在打印时,将for (int i = 0 ; i < 10; i++)循环替换为:

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

答案 1 :(得分:0)

您的错误在这里:

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

首先,在for循环中,您没有使用作为计数指示符的 i 变量。这意味着descending()方法没有任何 i 的意识,他如何能够返回不同的东西?

尝试修改descending(),如下所示:

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

    x =  b.toString();

    return x;
}