I'm trying to push any array list to a stack in reverse then concatenate a popped stacked. I getting the information from a file then storing it into an array List. Then i pushed the array List into a stack. now when i print the stack out its just printing the array List how can i pop the stack and concatenate it? here is my code so far
public static LinkedListStack myStack = new LinkedListStack();
public static void main(String[] args)
{
readFileLoadStack();
popStackPrintMsg();
}
public static void readFileLoadStack()
{
File afile; // For file input
Scanner keyboard = new Scanner(System.in); // For file input
String fileName; // To hold a file name
String line;
ArrayList song = new ArrayList<>();
boolean fileNotFound = true;
do
{
// Get a file name from the user.
System.out.println("Enter the name of the file");
fileName = keyboard.nextLine();
// Attempt to open the file.
try
{
afile = new File(fileName);
Scanner inFile = new Scanner(afile);
System.out.println("The file was found");
fileNotFound = false;
while (inFile.hasNextLine())
{
song.add(line = inFile.next());
}
for(int i = 0; i < song.size(); i++)
{
myStack.push1(song);
}
}
catch (FileNotFoundException e)
{
fileNotFound = true;
}
} while (fileNotFound);
}
public static void popStackPrintMsg()
{
if(!myStack.empty())
{
System.out.println(myStack.pop1());
} else
{
System.out.println("Sorry stack is empty");
}
}
output looks like this now :[Mary, had, a, little, lamb, Whose, fleece, was, white, as, snow, Everywhere, that, Mary, went, The, lamb, was, sure, to, go]
I'm trying to get it to look like this:
lamb little a had Mary
snow as white was fleece Whose
went Mary that Everywhere
go to sure was lamb The
i have made a custom class for the push and pop
{
private Node first;
/**
Constructs an empty stack.
*/
public LinkedListStack()
{
first = null;
}
/**
Adds an element to the top of the stack.
#param element the element to add
*/
public void push1(Object element)
{
Node newNode = new Node();
newNode.data = element;
newNode.next = first;
first = newNode;
}
/**
Removes the element from the top of the stack.
#return the removed element
*/
public Object pop1()
{
if (first == null) { throw new NoSuchElementException(); }
Object element = first.data;
first = first.next;
return element;
}
/**
Checks whether this stack is empty.
#return true if the stack is empty
*/
public boolean empty()
{
return first == null;
}
class Node
{
public Object data;
public Node next;
}
}
I fixed the problems in your code. Here is the working version along with some comments. This assumes the sentences in the file are separated by new lines and the words are separated by white spaces.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class GeneralTest {
//You want the same ordering for sentences. This collection
//therefore should be a list (or a queue)
//I have not changed the name so you can see how it makes a
//difference
public static List<LinkedListStack> myStack = new ArrayList<>();
public static void main(String[] args)
{
readFileLoadStack();
popStackPrintMsg();
}
public static void readFileLoadStack()
{
File afile; // For file input
Scanner keyboard = new Scanner(System.in); // For file input
String fileName; // To hold a file name
String line;
ArrayList song = new ArrayList<>();
boolean fileNotFound = true;
do
{
// Get a file name from the user.
System.out.println("Enter the name of the file");
fileName = keyboard.nextLine();
// Attempt to open the file.
try
{
afile = new File(fileName);
Scanner inFile = new Scanner(afile);
System.out.println("The file was found");
fileNotFound = false;
while (inFile.hasNextLine())
{
//Here you need to use nextLine() instead of next()
song.add(inFile.nextLine());
}
//This loop is the main location your original code goes wrong
//You need to create a stack for each sentence and add it to the
//list. myStack will hold a list of stacks after this loop is done
for(int i = 0; i < song.size(); i++)
{
String songString = (String) song.get(i);
String[] sga = songString.split(" ");
LinkedListStack rowStack = new LinkedListStack();
for(int j=0; j < sga.length; j++) rowStack.push1(sga[j]);
myStack.add(rowStack);
}
}
catch (FileNotFoundException e)
{
fileNotFound = true;
}
} while (fileNotFound);
}
public static void popStackPrintMsg()
{
//To get all values in a collection you need to
//loop over it. A single if will not work
for(LinkedListStack rs : myStack)
{
//Each entry in the list is a LinkedListStack
//So you can pop them and print the results with
//appropriate separators
while(!rs.empty())
System.out.print(rs.pop1() + " ");
System.out.println();
}
}
}
Now, your code has many other problems. For example, you really should use generics when you create a collection class.
The main problem with your code is that to produce the output you have described, you will need a queue of stacks. I have implemented the concept using ArrayList to show the source of the problem. But if you want to learn data structures (or if this is a homework problem), then you should try implementing and using a queue as well.
Related
Worksheet Question:
The question said to declare an array of 5 objects of the class Node in the main Class - I managed to this as shown below
But then the question continues populate the array by objects with seqNo values assigned to 1,2,3,4,5 respectively. Then traverse the array and print the list of its object using method show()
I have an error when I am trying to show the array to the user.
I am trying to display the array by this line of code:
nodObj[].show();
Below I have all the code except the Person class. Does someone have any idea if I should do a loop. When i tried if loop I got an error too. I have the display part code wrong I can't figure out what to change
My AnyClass
import java.util.Scanner;
public class AnyClass
{
public int seqNo;
/* -----------------Constructor------------*/
public AnyClass(int num)
{
seqNo = num; //initializing
}
//empty constructor
public AnyClass()
{
}
//intialized
public void initializeseqNo(int seqNum)
{
seqNum = seqNo;
}
/*-----Mehtods*/
public String getData()
{return "Sequence number " +seqNo+".";
}
public String getKey()
{
return String.valueOf(seqNo); //for search by seqNo
}
public void editData() //empty method to be overriden by future subcclasses
{
}
public void edit(){
Scanner sc = new Scanner(System.in);
seqNo = sc.nextInt();//next line for String
}
} //end of AnyClass
My Node class
public class Node
{
public AnyClass obj;
public Node(AnyClass newObj)
{
obj = newObj;
}
public void show()
{
System.out.println(obj.getData());
}
}
MainProg
class MainProg{
public static void main (String[] args) {
//-----------Construction of objects---------
Person head = new Person ("Gatt", 21445667);
Person clerk = new Person();
clerk.name = "Delia";
System.out.println ("Data of a new Head: " +head.getData());
AnyClass ac1 = new AnyClass(51);
AnyClass ac2 = new AnyClass(52);
AnyClass ac3 = new AnyClass(53);
ac1.getData();
ac2.getData();
ac3.getData();
//edit value of ac1
ac1.edit();
//print all values again
ac1.getData();
ac2.getData();
ac3.getData();
Node n = new Node(new AnyClass(3));
//print values
n.show();
Node nodObj[] = new Node[5]; //allocating memory to array
//populate array
nodObj[0] = new Node(new AnyClass(1));
nodObj[1] = new Node(new AnyClass(2));
nodObj[2] = new Node(new AnyClass(3));
nodObj[3] = new Node(new AnyClass(4));
nodObj[4] = new Node(new AnyClass(5));
//printing array
nodObj[].show(); //ERROR THIS IS WRONG!
}//end of Main()
}//end of program class
Below I have all the code except the Person class. Does someone have
any idea if I should do a loop. When i tried if loop I got an error
too. I have the display part code wrong I can't figure out what to
change
Yes, you need to loop over the array. At this level of instruction you should use a for or foreach loop.
for (int index = 0; index < nodObj.length; index++) {
nodObj[index].show();
}
Or
for (Node node : nodObj) {
node.show();
}
I read words from a text file and then create a new Word object for each word and store the objects into an ArrayList. The text of the word is passed into the object as a parameter. I have overridden the equals(Object) and hashCode() method of the word class to check for the equality of objects based on text of a word instead of object memory location. I am trying to store all unique words in ArrayList as unique objects and increment the occurrence of the word object if the word repeats in the text file.
Scanner file = new Scanner(new File(textfile));
ArrayList<Word> words = new ArrayList<Word>();
while (file.hasNext()) {
Word w = new Word(fileWord);
if (words.contains(w)) {
w.increaseCount();
} else {
words.add(w);
}
}
Word Class is;
public class Word {
private String text;
private int count;
public Word(String wordText) {
text = wordText;
}
public void increaseCount() {
count += 1;
}
#Override
public boolean equals(Object wordToCompare) {
if (wordToCompare instanceof Word) {
Word castedWord = (Word) wordToCompare;
if (castedWord.text.equals(this.text)) {
return true;
}
}
return false;
}
#Override
public int hashCode() {
return text.hashCode();
}
}
Unique words get added to the ArrayList, but my count does not increment. How to increment the count
The problem is with this statement in your code;
while (file.hasNext()) {
Word w = new Word(fileWord);
if (words.contains(w)) {
w.increaseCount(); // Here's what goes wrong.
} else {
words.add(w);
}
}
You're invoking the function increaseCount() on newly created object and that would get replaced during the next iteration, and you lost the reference. But the actual object is in the ArrayList and you should increase the value of that object. So, I would say, your code should be changed like this;
Scanner file = new Scanner(new File(textfile));
ArrayList<Word> words = new ArrayList<Word>();
while (file.hasNext()) {
Word w = new Word(fileWord);
if (words.contains(w)) {
words.get(words.indexOf(w)).increaseCount(); // Note the change here.
} else {
w.increaseCount(); // This is for the first occurrence as 'count' is 0 initially.
words.add(w);
}
}
The problem is that you create new instance of Word in the loop.
When the array contains the newly created Word, you increase the count for it, not the existing instance which already added to the array before.
Consider to use Map for the problem, the key is the word and the value is the count.
package example.stackoverflow;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class WordCount {
public static void main(String[] args) {
List<String> sourceList = Arrays.asList("ABC", "XYZ", "HGK", "ABC", "PWT", "HGK", "ABC");
Map<String, Integer> wordCount = new HashMap();
for (String word : sourceList) {
if (wordCount.get(word) != null) {
wordCount.put(word, wordCount.get(word) +1);
} else {
wordCount.put(word, 1);
}
}
System.out.println(wordCount);//output: {ABC=3, XYZ=1, PWT=1, HGK=2}
}
}
Check this answer:
Scanner file = new Scanner(new File(textfile));
ArrayList<Word> words = new ArrayList<Word>();
while (file.hasNext()) {
Word w = new Word(fileWord);
if (words.contains(w)) {
w.increaseCount();
int index = words.indexOf(w);
Word w1 = words.get(index);
w1.increaseCount();
words.set(index, w1);
} else {
words.add(w);
}
}
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.*;
//star my method lab
public class Method extends JPanel {
//two array lists that I am going to use.
ArrayList<String> english = new ArrayList<>();
ArrayList<String> french = new ArrayList<>();
//bring text file as an array
public void loadEnglishWords() {
//input my file
String filename = "english.txt";
File f = new File(filename);
try {
Scanner s = new Scanner(f);
//scan all array line by line
while (s.hasNextLine()) {
String line = s.nextLine();
english.add(line);
}
} catch (FileNotFoundException e) { //wrong file name makes error massage pop up
String errorMessage = "Wrong!";
JOptionPane.showMessageDialog(null, errorMessage, "Wrong!",JOptionPane.ERROR_MESSAGE);
}
}
//same array job with English to compare
public void loadFrenchWords() {
String filename = "french.txt";
File f = new File(filename);
try {
Scanner s = new Scanner(f);
while (s.hasNextLine()) {
String line = s.nextLine();
french.add(line);
}
} catch (FileNotFoundException e) {
String errorMessage = "Wrong!";
JOptionPane.showMessageDialog(null, errorMessage, "Wrong!",JOptionPane.ERROR_MESSAGE);
}
}
//check each line to parallel my arrays to get to same position
public String lookup(String word){
for (int i = 0; i < english.size();i++) {
if (word.equals(english.get(i))) {
return french.get(i);
}
}
//wrong values in arrays
return "No match found";
}
//infinite loop to run my program until get the result
public void mainLoop() {
while (true) {
//pop-up box to ask English words
String tmp = JOptionPane.showInputDialog("Please Enter an English Word!");
//store the result in variable r
String r = lookup(tmp);
String a;
//
if (r == ("No match found")) {
a = "Write a Right Word!";
} else {
a = "The French word is : " + r + ". Play agian?";
}
//asking want to play more or not
int result;
result = JOptionPane.showConfirmDialog(null,a,"RESULT!",JOptionPane.YES_NO_OPTION);
//doens't want to play then shut down
if (result == JOptionPane.NO_OPTION) {
break;
}
}
}
//make all things run in order
#Override
public void init() {
loadEnglishWords();
loadFrenchWords();
mainLoop();
}
}
//My problem is that everytime I compile this program the error message would be:
"Method.java:88: error: method does not override or implement a method from a supertype
#Override
^
1 error"
//This program is to translate french words to english words using arraylist
I`m using a .txt file for my set of english and french words and have it run through arraylist to translate
//In my program I need to use a JPanel or pop-up box to ask the user to input the word that they wish to translate
//Please note that I am a beginner with Java, please somebody help me and point out on where I got it wrong so I can change it. Thank you so much!
What the error is saying is that in line 88, you are using the #Override to redefine a method named init from parent class JPanel. But because JPanel is what it is (i.e. a part of Java), it does not have init method, you can not redefine it, hence the error. Most likely, you should just remove the #Override, which will mean you want to add a new method instead of redefining it.
Inheritance is a mechanism where you take an existing class and modify it according to your needs. In your case, your class is named Method and it extends (inherits from) JPanel, so JPanel is the supertype of your class.
If you're just beginning, go read and educate yourself on object-oriented concepts. There are many tutorials, including YouTube videos. Happy learning!
Aside from what was previously mentioned, you need to change a few things:
public void init() { should be public static void main(String args[]) {
Then you need to make your methods static, i.e.
public static void loadEnglishWords() {
Also, the arrayLists need to also be static
And one other thing, you should compare with .equals() and not ==
I've re-written your code slightly and now it should work:
static ArrayList<String> english = new ArrayList<>();
static ArrayList<String> french = new ArrayList<>();
//bring text file as an array
public static void loadEnglishWords() {
//input my file
try {
Scanner s = new Scanner(new File("english.txt"));
//scan all array line by line
while (s.hasNextLine()) {
String line = s.next();
english.add(line);
}
} catch (FileNotFoundException e) { //wrong file name makes error massage pop up
String errorMessage = "Wrong!";
JOptionPane.showMessageDialog(null, errorMessage, "Wrong!", JOptionPane.ERROR_MESSAGE);
}
}
//same array job with English to compare
public static void loadFrenchWords() {
try {
Scanner s = new Scanner(new File("french.txt"));
while (s.hasNextLine()) {
String line = s.nextLine();
french.add(line);
}
} catch (FileNotFoundException e) {
String errorMessage = "Wrong!";
JOptionPane.showMessageDialog(null, errorMessage, "Wrong!", JOptionPane.ERROR_MESSAGE);
}
}
//check each line to parallel my arrays to get to same position
public static String lookup(String word) {
for (int i = 0; i < english.size(); i++) {
if (word.equals(english.get(i))) {
return french.get(i);
}
}
//wrong values in arrays
return "No match found";
}
//infinite loop to run my program until get the result
public static void mainLoop() {
while (true) {
//pop-up box to ask English words
String tmp = JOptionPane.showInputDialog("Please Enter an English Word!");
//store the result in variable r
String r = lookup(tmp);
String a;
//
if (r.equals("No match found")) {
a = "Write a Right Word!";
} else {
a = "The French word is : " + r + ". Play agian?";
}
//asking want to play more or not
int result;
result = JOptionPane.showConfirmDialog(null, a, "RESULT!", JOptionPane.YES_NO_OPTION);
//doens't want to play then shut down
if (result == JOptionPane.NO_OPTION) {
break;
}
}
}
//make all things run in order
public static void main(String args[]) {
loadEnglishWords();
loadFrenchWords();
mainLoop();
}
}
I have a file with the following:
5
212:Float On:Modest Mouse
259:Cherub Rock:Smashing Pumpkins
512:Won't Get Fooled Again:The Who
417:Teen Age Riot:Sonic Youth
299:PDA:Interpol
I need to create a array but I need to take into account the integer it starts with, then read the rest as strings taking into account the initial line containing only an integer. I've made the method to read the file and print, just don't know how to split it up.
An example of how to do it:
String s = "212:Float On:Modest Mouse"; // your input - a line from the file
String[] arr = s.split(":");
System.out.println(arr[0]); // your int
// The rest of the array elements will be the remaining text.
// You can concatenate them back into one string if necessary.
you can read file using Scanner
readlines = new Scanner(filename);
while(readlines.hasNextLine())
{
String line = readlines.nextLine();
String[] values = line.split(":");
int firstColumn = -1;
if (values.length > 0) {
try {
firstColumn = Integer.parseInt(values[0]);
} catch (NumberFormatException ex) {
// the value in the first column is not an integer
}
}
}
I've grown a habit of reading the entire file into a List, then handling the List in memory. Doing this is not the only option.
Once I have the file read in, I look at the first line to know how many tracks to expect in the remaining file. I then would loop through the remaining List to either get the number of tracks from the first line or until I reach the end of the list, in the event that the number of tracks (from the first line) exceeds the actual amount of tracks that are in the file.
As I go through the tracks I would use substring to break the line apart, and convert just the first part.
Update
Base on your comment, I've updated to use split instead of substring. Then some basic alignment formatting for output
public static void main(String[] args) throws Exception {
String yourFile = "path to your file.txt";
List<String> yourFileLines = new ArrayList<>(Files.readAllLines(Paths.get(yourFile)));
// You know the first line is suppose to be the number of tracks so convert it to a number
int numberOfTracks = Integer.valueOf(yourFileLines.get(0));
// Either go to the number of tracks or till the end of file
List<Track> tracks = new ArrayList<>();
for (int i = 1; (i <= numberOfTracks && i < yourFileLines.size()); i++) {
String currentFileLine = yourFileLines.get(i);
String[] currentFileLinePieces = currentFileLine.split(":");
Track currentTrack = new Track();
currentTrack.TrackTime = Integer.valueOf(currentFileLinePieces[0]);
currentTrack.TrackTitle = currentFileLinePieces[1];
currentTrack.TrackArtist = currentFileLinePieces[2];
tracks.add(currentTrack);
}
System.out.println(String.format("%-20s\t\t%-20s\t\t%-20s", "TITLE", "ARTIST", "TIME"));
System.out.println(String.format("%-20s\t\t%-20s\t\t%-20s", "-----", "------", "----"));
for (Track currentTrack : tracks) {
System.out.println(currentTrack);
}
}
public static class Track {
public int TrackTime;
public String TrackTitle;
public String TrackArtist;
#Override
public String toString() {
return String.format("%-20s\t\t%-20s\t\t%-20d", TrackTitle, TrackArtist, TrackTime);
}
}
Results:
Here's an example using a Scanner, and breaking everything into methods. You should be able to use List and ArrayList. Results are the same.
public static void main(String[] args) throws Exception {
String yourFile = "data.txt";
List<String> yourFileLines = readFile(yourFile);
if (yourFileLines.size() > 0) {
// You know the first line is suppose to be the number of tracks so convert it to a number
int numberOfTracks = Integer.valueOf(yourFileLines.get(0));
List<Track> tracks = getTracks(numberOfTracks, yourFileLines);
printTracks(tracks);
}
}
public static List<String> readFile(String pathToYourFile) {
List<String> yourFileLines = new ArrayList();
try {
File yourFile = new File(pathToYourFile);
Scanner inputFile = new Scanner(yourFile);
while(inputFile.hasNext()) {
yourFileLines.add(inputFile.nextLine().trim());
}
} catch (Exception e) {
System.out.println(e);
}
return yourFileLines;
}
public static List<Track> getTracks(int numberOfTracks, List<String> yourFileLines) {
List<Track> tracks = new ArrayList();
// Either go to the number of tracks or till the end of file
for (int i = 1; (i <= numberOfTracks && i < yourFileLines.size()); i++) {
String currentFileLine = yourFileLines.get(i);
String[] currentFileLinePieces = currentFileLine.split(":");
Track currentTrack = new Track();
currentTrack.TrackTime = Integer.valueOf(currentFileLinePieces[0]);
currentTrack.TrackTitle = currentFileLinePieces[1];
currentTrack.TrackArtist = currentFileLinePieces[2];
tracks.add(currentTrack);
}
return tracks;
}
public static void printTracks(List<Track> tracks) {
System.out.println(String.format("%-20s\t\t%-20s\t\t%-20s", "TITLE", "ARTIST", "TIME"));
System.out.println(String.format("%-20s\t\t%-20s\t\t%-20s", "-----", "------", "----"));
for (Track currentTrack : tracks) {
System.out.println(currentTrack);
}
}
public static class Track {
public int TrackTime;
public String TrackTitle;
public String TrackArtist;
#Override
public String toString() {
return String.format("%-20s\t\t%-20s\t\t%-20d", TrackTitle, TrackArtist, TrackTime);
}
}
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.
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.
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.
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.
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:
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:
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. 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();
*/
}