简体   繁体   English

通过对象字段过滤/排序集合?

[英]Filtering/sorting a collection through object fields?

I'm not sure why this isn't working. 我不确定为什么这行不通。 I'm not sure if it's a problem with the printing, or if it's a problem with the methods themselves. 我不确定这是打印问题还是方法本身的问题。 I am making a program that takes a collection of songs and filters or sorts it according to a given user input. 我正在制作一个程序,该程序可以接收歌曲并进行过滤或根据给定的用户输入对其进行排序。 The user should be able to input multiple commands to further narrow down the list. 用户应该能够输入多个命令来进一步缩小列表范围。

My filterRank and filterYear methods work perfectly fine, but the other methods end up printing a seemingly random selection of songs that do not change regardless of what is inputted as the title or artist to be filtered by, which generally appears only after an extremely long waiting period and a long series of spaces. 我的filterRank和filterYear方法可以很好地工作,但是其他方法最终会打印看似随机的歌曲,这些歌曲无论输入什么作为标题或艺术家,都不会改变,通常仅在等待了很长时间之后才会出现周期和一连串的空格。

Even after this amalgam of songs is printed, the program does not terminate, and periodically outputs a space in the console, as in a System.out.println() statement were being continuously run. 即使在打印出这种混合的歌曲之后,该程序也不会终止,并且会在控制台中定期输出一个空格,因为System.out.println()语句正在连续运行。

If I remove the code that configures the output file, which is a requirement for the project, the methods fail to print entirely. 如果我删除了配置输出文件的代码(这是项目的要求),则方法将无法完全打印。 Regardless of either of these changes, filterRank and filterYear continue to work perfectly. 无论这些更改如何,filterRank和filterYear都可以继续正常运行。

This problem also occurs with my sort methods. 我的排序方法也会出现此问题。 No matter what sort method I run, it still prints out the spaces and the random songs, or nothing at all. 无论我使用哪种排序方法,它都仍然会打印出空格和随机歌曲,或者什么也不会打印。

Is there something I'm missing? 有什么我想念的吗? I've tried printing out variables and strategically inserting System.out.println("test") in my program to determine what the program is, but it seems as though it's parsing the input correctly, and the methods are indeed being successfully run. 我尝试打印出变量,并从策略上在程序中插入System.out.println(“ test”)来确定程序是什么,但是似乎它可以正确解析输入,并且方法确实可以成功运行。 I've been otherwise unable to isolate the problem. 我一直无法解决问题。

Can I get assistance in determining what I'm missing? 我可以在确定我缺少的东西上获得帮助吗? Despite poring over my code for two hours, I just can't figure out what the logical error on my part is. 尽管花了两个小时研究我的代码,但我还是无法弄清楚我的逻辑错误是什么。

Here is the relevant code: 以下是相关代码:

The main class: 主班:

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

The SongCollection Class, with all of its respective filter and sort methods: SongCollection类,及其所有相应的filter和sort方法:

  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 Class: 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");
    }

}

After you output the filtered collection, your program doesn't terminate because you are still in a while loop looking for the next user input line. 输出过滤的集合之后,您的程序不会终止,因为您仍处于while循环中,寻找下一个用户输入行。 This is basically what your program is doing: 这基本上是您的程序正在执行的操作:

    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();
         */
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM