【问题标题】:Filtering/sorting a collection through object fields?通过对象字段过滤/排序集合?
【发布时间】:2014-04-30 06:17:01
【问题描述】:

我不确定为什么这不起作用。我不确定这是打印的问题,还是方法本身的问题。 我正在制作一个程序,它需要一组歌曲和过滤器,或者根据给定的用户输入对其进行排序。用户应该能够输入多个命令以进一步缩小列表范围。

我的 filterRank 和 filterYear 方法工作得很好,但其他方法最终打印出看似随机的歌曲选择,无论输入什么作为要过滤的标题或艺术家,这些歌曲通常只出现在极长的等待期和一长串的空间。

即使在打印完这些歌曲后,程序也不会终止,并会定期在控制台中输出一个空格,就像 System.out.println() 语句不断运行一样。

如果我删除配置输出文件的代码,这是项目的要求,这些方法将无法完全打印。无论这些更改如何,filterRank 和 filterYear 都可以继续完美运行。

我的排序方法也会出现这个问题。无论我运行哪种排序方法,它仍然会打印出空格和随机歌曲,或者什么都不打印。

我有什么遗漏吗?我已经尝试打印出变量并在我的程序中策略性地插入 System.out.println("test") 以确定程序是什么,但似乎它正在正确解析输入,并且这些方法确实正在成功运行。 我一直无法隔离问题。

我可以在确定我缺少什么方面获得帮助吗?尽管仔细研究了我的代码两个小时,我还是无法弄清楚我的逻辑错误是什么。

以下是相关代码:

主类:

public static void main(String[] args) throws FileNotFoundException, IOException{

//user greeting statements and instructions
//scanning file, ArrayList declaration


    Scanner input = new Scanner(System.in);

    while (input.hasNextLine()) {
        int n = 0;
        SongCollection collection = new SongCollection(songs);
        String inputType = input.nextLine();
        String delims = "[ ]";
        String[] tokens = inputType.split(delims);
        for (int i = 0; i < tokens.length; i++) {
            n = 0;
            if (n == 0) {
                if ((tokens[i]).contains("year:")) {
                    collection.filterYear(Range.parse(tokens[i]));
                    n = 1;
                }// end of year loop
                if ((tokens[i]).contains("rank:")) {
                    collection.filterRank(Range.parse(tokens[i]));
                    n = 1;
                }// end of rank
                if ((tokens[i]).contains("artist:")) {
                    collection.filterArtist(tokens[i]);
                    n = 1;
                }// end of artist
                if ((tokens[i]).contains("title:")) {
                    collection.filterTitle(tokens[i]);
                    n = 1;
                }// end of title
                if ((tokens[i]).contains("sort:")) {
                        if ((tokens[i]).contains("title")) {
                            collection.sortTitle();
                            n = 1;
                        }// end of sort title
                        if ((tokens[i]).contains("artist")) {
                            collection.sortArtist();
                            n = 1;
                        }// end of sort artist
                        if ((tokens[i]).contains("rank")) {
                            collection.sortRank();
                            n = 1;
                        }// end of sort rank
                        if ((tokens[i]).contains("year")) {
                            collection.sortYear();
                            n = 1;
                        }// end of sort year
                }//end of sort
            }// end of for loop

        }// end of input.hasNextline loop
        /*final PrintStream console = System.out; //saves original System.out
        File outputFile = new File("output.txt"); //output file
        PrintStream out = new PrintStream(new FileOutputStream(outputFile)); //new FileOutputStream
        System.setOut(out); //changes where data will be printed
           */           System.out.println(collection.toString()); 

        /*System.setOut(console); //changes output to print back to console
        Scanner outputFileScanner = new Scanner(outputFile); //inputs data from file
        while ((outputFileScanner.hasNextLine())) { //while the file still has data
            System.out.println(outputFileScanner.nextLine()); //print
        }
        outputFileScanner.close();
        out.close();*/
    }
}// end of main
}// end of class

SongCollection 类,及其所有各自的过滤器和排序方法:

  import java.io.File;
   import java.io.FileNotFoundException;
   import java.util.*;


    public class SongCollection {
ArrayList<Song> songs2;
ArrayList<Song> itemsToRemove = new ArrayList<Song>(); // second collection
                                                        // for items to
                                                        // remove
public SongCollection(ArrayList<Song> songs) { // constructor for SongCollection
    System.out.println("Test"); 
    this.songs2 = songs;
    }
public void filterYear(Range r) {
    int n = 0;
    if (n == 0) {
        System.out.println("Program is processing.");
        n++;
        for (Song song1 : songs2) {
            if (song1.year > (r.getMax()) || (song1.year) < (r.getMin())) {
                itemsToRemove.add(song1);
            }
        }
        songs2.removeAll(itemsToRemove);
        itemsToRemove.clear();
    }
}

public void filterRank(Range r) {
    int n = 0;
    if (n == 0) {
        System.out.println("Program is processing.");
        n++;
        for (Song song1 : songs2) {
            if (song1.rank > (r.getMax()) || (song1.rank) < (r.getMin())) {
                itemsToRemove.add(song1);
            }
        }
        songs2.removeAll(itemsToRemove);
        itemsToRemove.clear();
    }
}

public void filterArtist(String s) {
    int n = 0;
    if (n == 0) {
        System.out.println("Program is processing.");
        n++;
        for (Song song1 : songs2) {
            if ((!(((song1.artist).contains(s))))) {
                itemsToRemove.add(song1);
            }
        }
        songs2.removeAll(itemsToRemove);
        itemsToRemove.clear();
    }
}

public void filterTitle(String s) {
    int n = 0;
    if (n == 0) {
        System.out.println("Program is processing.");
        n++;
        for (Song song1 : songs2) {
            if ((!(((song1.title).contains(s))))) {
            itemsToRemove.add(song1);
            }
        }
        songs2.removeAll(itemsToRemove);
        itemsToRemove.clear();
    }
}

public void sortTitle() {
      Collections.sort(songs2, SongComparator.byTitle()); // now we have a sorted list
    }
public void sortRank() {
      Collections.sort(songs2, SongComparator.byRank()); // now we have a sorted list
    }
public void sortArtist() {
      Collections.sort(songs2, SongComparator.byArtist()); // now we have a sorted list
    }
public void sortYear() {
      Collections.sort(songs2, SongComparator.byYear()); // now we have a sorted list
    }
public String toString() {
    String result = "";
    for (int i = 0; i < songs2.size(); i++) {
        result += " " + songs2.get(i);
    }

    return result;

}
}

SongComparator 类:

import java.util.Comparator;

public class SongComparator implements Comparator<Song> {
public enum Order{
    YEAR_SORT, RANK_SORT, ARTIST_SORT, TITLE_SORT
}
private Order sortingBy;
public SongComparator(Order sortingBy){
    this.sortingBy = sortingBy;
}
public static SongComparator byTitle() {
    return new SongComparator(SongComparator.Order.TITLE_SORT);
}
public static SongComparator byYear() {
    return new SongComparator(SongComparator.Order.YEAR_SORT);
}
public static SongComparator byArtist() {
    return new SongComparator(SongComparator.Order.ARTIST_SORT);
}
public static SongComparator byRank() {
    return new SongComparator(SongComparator.Order.RANK_SORT);
}

@Override
public int compare(Song song1, Song song2) {
    switch (sortingBy) {
    case YEAR_SORT:
        System.out.println("test");
        return Integer.compare(song1.year, song2.year);
    case RANK_SORT:
        System.out.println("test");
        return Integer.compare(song1.rank, song2.rank);
    case ARTIST_SORT:
        System.out.println("test");
        return song1.artist.compareTo(song2.artist);
    case TITLE_SORT:
        System.out.println("test");
        return song1.title.compareTo(song2.title);
    }
    throw new RuntimeException(
            "Practically unreachable code, can't be thrown");
    }

}

【问题讨论】:

  • 您发布的代码非常多。使用您的调试器,并隔离代码中有问题的部分。
  • 过滤器中的这个 n=0 是什么?
  • 我正在尝试使用一种电灯开关方法。如果该命令已经运行,它将不会再次运行,直到 while 循环重置它。
  • 恐怕我们还没有在课堂上学会如何使用调试器。
  • 除非您隔离问题并删除所有不相关的内容,否则不会有很多人愿意阅读您的代码并帮助您。你应该首先证明你已经做了尽可能多的事情。

标签: java sorting collections arraylist filter


【解决方案1】:

在您输出过滤后的集合后,您的程序不会终止,因为您仍在寻找下一个用户输入行的 while 循环。这基本上就是您的程序正在做的事情:

    while (input.hasNextLine()) {

        // stuff happens here

        System.out.println(collection.toString());

        /*
         * System.setOut(console); //changes output to print back to console Scanner outputFileScanner = new Scanner(outputFile); //inputs data from file while ((outputFileScanner.hasNextLine()))
         * { //while the file still has data System.out.println(outputFileScanner.nextLine()); //print } outputFileScanner.close(); out.close();
         */
    }

【讨论】:

  • 这是有道理的。但是,它为什么没有打印出过滤/排序的集合,以及为什么这些神秘的空间不断弹出?
猜你喜欢
  • 2021-10-27
  • 1970-01-01
  • 2017-03-07
  • 1970-01-01
  • 2013-05-11
  • 2013-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多