Java array values gets overwritten - java

I am new to Java and this is a very basic question.
However I struggle to find a solution, so hopefully someone could give me some pointers.
I am trying to fill values into an array "addedPlayer".
However, every time I run the AddPlayer() method it is initialiezed to zero again.
How can I structure this in a better way?
public class DemoApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
public void AddPlayer() {
int[] addedPlayer;
addedPlayer = new int[500];
System.out.println(" *** Add new player *** ");
System.out.println("Name:");
String name = System.console().readLine();
System.out.println("Age:");
int age = Integer.parseInt(System.console().readLine());
System.out.println("JNUM:");
int jnum = Integer.parseInt(System.console().readLine());
player p = new player();
p.SetAge(age);
p.SetName(name);
p.SetJnum(jnum);
System.out.println(addedPlayer[0]);
for (int j = 0; j < addedPlayer.length; j++) {
if (addedPlayer[j] != 0) {
} else {
addedPlayer[j] = p.GetAge();
System.out.println(addedPlayer[j]);
System.out.println(j);
break;
}
}
}
public void EditPlayer() {
//empty
}
public void ListPlayer() {
//empty
}
#Override
public void run(String... args) throws Exception {
while (true) {
System.out.println(" *** MENY *** ");
System.out.println(" 1. Add player ");
System.out.println(" 2. Edit player ");//ÖKurs
System.out.println(" 3. List player ");
System.out.println(" 100. Exit ");
System.out.println("Ange val");
int sel = Integer.parseInt(System.console().readLine());
if (sel == 100) break;
if (sel == 1) AddPlayer();
if (sel == 2) EditPlayer();
if (sel == 3) AddPlayer();
}
}
}

Each time you run AddPlayer(), it creates a new player from scratch. If you want to keep your modifications to a bare minimum, you must put it outside of the method and make it a property for your class like List<int[]> addedPlayers = new ArrayList<int[]>(); and you can add this line AddPlayer to add it in a list addedPlayers.add(addedPlayer). Otherwise, if you want a more cleaner code, you should add more classes than only one main class. To improve your code, you can see #g.momo's answer.

int[] addedPlayer; addedPlayer = new int[500];
It gets overridden because you are creating an new local var addedPlayer, and then setting all values to 0 (addedPlayer = new int[500];) I'm assuming you would want addedPlayer to be global, so don't define it locally and set it to 0.
Also, should addedPlayer be a player[] or just a player rather than an int[]? Plus, you didn't close the function in the code you gave us, so is there more missing or did you just not close it?

Your code and your expectations are completely differents.
Read this and tell us if you understand. It is the way I would have written if I were you . But it is NOT TESTED:
public class AddPlayer { // you create a class
player[] addedPlayer; // array of players
int index;
public AddPlayer() { // constructor of the class
addedPlayer = new player[500]; // max 500 players
index = 0;
}
public void addPlayer(player p) {
if(index < 500) {
addedPlayer[index] = p; // add at index,
index = index + 1; // then increment index for the next added player
}
}
public static void main(String... args) {
AddPlayer addPlayers = new AddPlayer();
int i = 0;
while(i < 5) { // will run 5 times, so only 5 players will be added. Change to stop when you will need
// here your read console inputs
System.out.println(" *** Add new player *** "+ (i+1));
System.out.println("Name:");
String name = System.console().readLine();
System.out.println("Age:");
int age = Integer.parseInt(System.console().readLine());
System.out.println("JNUM:");
int jnum = Integer.parseInt(System.console().readLine());
// initialize the player
player p = new player();
p.SetAge(age);
p.SetName(name);
p.SetJnum(jnum);
addPlayers.addPlayer(p); // add in the array
i++;
}
}
}

Related

JAVA error cannot find a symbol

I need to create a JAVA method: public static int[] Numb() that reads and returns a series of positive integer values. If the user enters -1 we should stop accepting values, and then I want to call it in the main method. And we should return to the user integers that he entered them, with the total number.
So if he entered the following:
5 6 1 2 3 -1
So the total number is : 6
The numbers entered are: 5 6 1 2 3 -1
I tried the following:
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
}
public static int[] readNumbers(int[] n)
{
int[] a = new int[n.length];
Scanner scan = new Scanner(System.in);
for(int i = 0;i<n.length;i++) {
String token = scan.next();
a[i] = Integer.nextString();
}
}
}
And here is a fiddle of them. I have an error that said:
Main.java:21: error: cannot find symbol
a[i] = Integer.nextString();
I am solving this exercise step by step, and I am creating the method that reads integers. Any help is appreciated.
Integer.nextString() doesn't exist, to get the next entered integer value, you may change your loop to either :
for(int i = 0;i<n.length;i++) {
a[i] = scan.nextInt();
}
or as #vikingsteve suggested :
for(int i = 0;i<n.length;i++) {
String token = scan.next();
a[i] = Integer.parseInt(token);
}
public static void main(String[] args) {
List<Integer> numList = new ArrayList<>();
initializeList(numList);
System.out.println("Num of integer in list: "+numList.size());
}
public static void initializeList(List<Integer> numList) {
Scanner sc = new Scanner(System.in);
boolean flag = true;
while(flag) {
int num = sc.nextInt();
if(num==-1) {
flag = false;
}else {
numList.add(num);
}
}
sc.close();
}
Since the number of integers is unknown, use ArrayList. It's size can be altered unlike arrays.
You can create something like arraylist on your own..it can be done like this:
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
CustomArray c = new CustomArray(3);
boolean flag = true;
while (flag) {
int num = sc.nextInt();
if (num == -1) {
flag = false;
} else {
c.insert(num);
}
System.out.println(Arrays.toString(c.numList));
}
sc.close();
}
}
class CustomArray {
int[] numList;
int size; // size of numList[]
int numOfElements; // integers present in numList[]
public CustomArray(int size) {
// TODO Auto-generated constructor stub
numList = new int[size];
this.size = size;
numOfElements = 0;
}
void insert(int num) {
if (numOfElements < size) {
numList[numOfElements++] = num;
} else {
// list is full
size = size * 2; //double the size, you can use some other factor as well
//create a new list with new size
int[] newList = new int[size];
for (int i = 0; i < numOfElements; i++) {
//copy all the elements in new list
newList[i] = numList[i];
}
numList = newList;//make numList equal to new list
numList[numOfElements++] = num;
}
}
}

Java 2 player trivia game

I am having some trouble with this, and I would greatly appreciate some help. I am still a "noobie" when it comes to java so please understand that I probably will have stupid mistakes. Anyways, I am trying to make a two player java game and I keep getting errors that I do not understand. I have three separate classes. This is my main class
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Assignment3
{
public static void main(String args[]) throws IOException
{
// Constants
final int NUM_QUESTIONS = 10;
final int NUM_PLAYERS = 2;
// Variables
int playerTurn = 1; // The current player
int questionNum; // The current question number
int playerAnswer; // The player's chosen answer
int player1points = 0; // Player 1's points
int player2points = 0; // Player 2's points
// Create an array of Player objects for player #1 and player #2.
player[] players = new player[NUM_PLAYERS];
for (int i = 0; i < NUM_PLAYERS; i++)
{
players[i] = new player(i+1);
}
// Create an array to hold Question objects.
questions[] questions = new questions [NUM_QUESTIONS];
// Initialize the array with data.
intQuestion(questions);
// Play the game.
for (int i = 0; i < NUM_QUESTIONS; i++)
{
// Display the question.
Assignment3.displayQuestion(qArray[i], playerTurn);
// Get the player's answer.
players[playerTurn - 1].chooseAnswer();
// See if the correct answer was chosen.
if (qArray[i].getCorrectAnswerNumber() == players[playerTurn - 1].getCurrentAnswer())
{
players[playerTurn -1].incrementPoints();
}
// See if the the player chose the wrong answer.
// do nothing
// Switch players for the next iteration.
if (playerTurn == 1)
playerTurn = 2;
else
playerTurn = 1;
}
// Show the game results.
showGameResults(players);
}
/**
* The initQuestions method uses the contents of the trivia.txt file to
* populate the qArray parameter with Question objects.
*/
public static void initQuestions(questions qArray[]) throws IOException
{
// Open the trivia.txt file.
File file = new File("trivia.txt");
Scanner inputFile = new Scanner(file);
// Populate the qArray with data from the file.
for (int i = 0; i < qArray.length; i++)
{
// Create a Question object in the array.
qArray[i] = new questions();
// Get the question text from the file.
qArray[i].setQuestion(inputFile.nextLine());
// Get the possible answers.
for (int j = 1; j <= 4; j++)
{
qArray[i].setPossibleAnswer(inputFile.nextLine(), j);
}
// Get the correct answer.
qArray[i].setCorrectAnswerNumber(Integer.parseInt(inputFile.nextLine()));
}
}
public static void displayQuestion(questions q, int playerNum)
{
// Display the player number.
System.out.println("Question for player #" + playerNum);
System.out.println("------------------------");
// Display the question.
System.out.println(q.getQuestionText());
for (int i = 1; i <= 4; i++)
{
System.out.println(i + ". " + q.getPossibleAnswer(i));
}
}
public static void showGameResults(player[] players)
{
// Display the stats.
System.out.println("Game Over!");
System.out.println("---------------------");
System.out.println("Player 1's points: " + players[0].getPoints());
System.out.println("Player 2's points: " + players[1].getPoints());
// Declare the winner.
if (players[0].getPoints() > players[1].getPoints())
System.out.println("Player 1 wins!");
else if (players[1].getPoints() > players[0].getPoints())
System.out.println("Player 2 wins!");
else
System.out.println("It's a TIE!");
}
}
This is my player class
import java.util.Scanner;
public class player
{
private int playerNumber; // The player number
private int points; // Player's points
private int currentAnswer; // Current chosen answer
//Constructor
public player(int playerNum)
{
playerNumber = playerNum;
points = 0;
}
public void chooseAnswer()
{
// Create a Scanner object for keyboard input.
// Get the user's chosen answer.
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter your Answer"); //Asks user for a number
this.currentAnswer = keyboard.nextInt();
}
public int getCurrentAnswer()
{
return this.currentAnswer; //Returns Current Answer
}
public void incrementPoints()
{
this.points++; //Increments the points
}
public int getPoints()
{
return this.points; //Returns the points
}
}
This is my questions class
public class questions
{
// Constant for the number of answers
public final int NUM_ANSWERS = 10;
// The trivia question
private String questionText;
// An array to hold possible answers.
private String possibleAnswers[] = new String[NUM_ANSWERS];
// The number (1, 2, 3, or 4) of the correct answer.
private int correctAnswer;
//Constructor
public questions()
{
// Initialize all fields to "" or 0;
questionText = "";
correctAnswer = 0;
for (int i = 1; i < NUM_ANSWERS; i++)
setPossibleAnswer("", i);
}
public void setQuestion(String question)
{
//Sets the question
this.questionText = question;
}
public void setPossibleAnswer(String text, int num)
{
//Sets possible Answer
this.possibleAnswers[num] = text;
}
public void setCorrectAnswerNumber(int num)
{
//Sets correct Answer
this.correctAnswer = num;
}
public String getQuestionText()
{
//Returns Question Text
return this.questionText;
}
public String getPossibleAnswer(int num)
{
//Returns Possible Amswer
return this.possibleAnswers[num];
}
public int getCorrectAnswerNumber()
{
//Returns Correct Answer
return this.correctAnswer;
}
public String getCorrectAnswer()
{
//Returns Possible Answer
return this.possibleAnswers[this.correctAnswer];
}
}
If there is any help you guys can offer, I would greatly appreciate. I just can't seem to figure out why I keep getting these errors that are stopping it from running. Please and thank you.
these are the errors I get, I don't know if this is what you mean, I found out what I had earlier was from something else
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method intQuestion(questions[]) is undefined for the type Assignment3
qArray cannot be resolved to a variable
qArray cannot be resolved to a variable
at Assignment3.main(Assignment3.java:42)
Your method is named initQuestion, but you are calling intQuestion.
Oh, and you are using qArray outside of initQuestion, the only place where it seems to be defined.

Java - Creating Object Arrays [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I can't seem to work out these object arrays, I'm attempting to create a list of player names with values stored, each with an integer and some multiple strings for each.
This is what i'm working on so far, were object arrays the correct storage package for this? The error was in line 237 when I try to add a player in the class addPlayer: player[userCount].setName(name);
The error is:- Exception in thread "main" index out of bounds.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class PlayerKarma {
static Scanner input = new Scanner(System.in);
static private String[] username = {"name1","name2","test","moretesting","fervor","stackoverflow","imported","quaternion","jetstream"};
static private int[] karma = {1000,800,800,5,15,-4,-403,54,11,210};
static private boolean exit = false;
static private int maxKarmaChange = 10; //How much a players karma can change per day.
static Player[] userArray = new Player[10000];
//ArrayList<Player> userArray = new ArrayList<Player>();
static private int userCount = 0;
public static void main(String[] args)
{
while (!exit)
{
System.out.println("");
System.out.println("Select an option");
System.out.println("1: Display a player's karma");
System.out.println("3: Display all player names and karma");
System.out.println("5: Add player");
String command = input.nextLine();
switch(command)
{
//Display player's karma.
case "1": {
System.out.println("Enter a player's name: ");
String inputString = input.nextLine();
int playerindex = findPlayer(inputString);
if (playerindex == -1)
{
System.out.println("Player doesn't exist");
}
else //If the player exists.
{
System.out.println(userArray[playerindex].getName() + " has a karma of " + karma[userArray[playerindex].getKarma()]);
break;
}
break;}
//Display all player names and karma.
case "3": {getAllPlayerKarma(); sleep(1500); break;}
//Add player.
case "5": {
System.out.println("Enter a player's name:");
String inputString = input.nextLine();
if (userCount > 0) //If there is at least one user in the database.
{
int playerindex = findPlayer(inputString);
if (playerindex == -1)
{
addPlayer(inputString,0);
}
else //If the player exists.
{
break;
}
}
else //If there's no users.
{
addPlayer(inputString,0);
}
break;}
}
}
}
//Class creation for players.
public class Player
{
public String name;
public int karma;
//public String[] notes = new String[5];
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getKarma() {
return karma;
}
public void setKarma(int karma) {
this.karma = karma;
}
}
private static void getAllPlayerKarma() {
System.out.println("");
for (int k = 0; k < userCount; k++)
{
System.out.println(userArray[k].getName() + " has a karma of " + userArray[k].getKarma());
}
}
private static void setAllPlayerKarma(String karmaValue) {
System.out.println("");
for (int k = 0; k < username.length; k++)
{
int parseKarma = Integer.parseInt(karmaValue);
karma[k] = parseKarma;
}
System.out.println("All karma has been set to " + karmaValue);
}
private static void addPlayer(String name, int karma) {
//Adds a new user
Player[] player = new Player[userCount];
//Player[userCount] = new Player(userCount);
player[userCount].setName(name);
player[userCount].setKarma(karma);
//userArray[userCount].setName(name);
//userArray[userCount].setKarma(karma);
userCount++;
}
//Returns the index of the player in the database.
private static int findPlayer(String playerName) {
int playerIndex = -1;
for (int j = 0; j < userCount; j++)
{
System.out.println("Testing name: " + playerName + " against " + userArray[j].getName());
if (playerName.equals(userArray[j].getName())) {
playerIndex = j;
System.out.println("Match");
break;
}
else
{
//System.out.println("No match");
}
}
return playerIndex;
}
private static void sleep(int sleep) {
try {Thread.sleep(sleep);}
catch(InterruptedException ex) {
Thread.currentThread().interrupt();}
}
}
There are three problems with this code:
Player[] player = new Player[userCount];
player[userCount].setName(name);
Firstly, you're creating a new array each time - I suspect you want to populate userArray instead.
Secondly, you're creating an array of size userCount and then trying to use the element with index userCount - that's never going to work. Array indexes are 0-based, so an element with length 3 has valid indexes 0, 1 and 2 for example.
Thirdly, you're not creating a new Player object - so every element in the array is null. Even if you fixed the index, player[x].setKarma(karma) would throw a NullPointerException.
I suspect you want the method to look like this:
private static void addPlayer(String name, int karma) {
Player player = new Player();
player.setKarma(karma);
player.setName(name);
userArray[userCount] = player;
userCount++;
}
That's now fine, until the user count exceeds the length of your array. At that point, you should start looking at List<E> (and ArrayList<E> in particular).
You initialize usercount with the value of 0 and therefore create an array with the size of 0 Player[] player = new Player[userCount];, this leads to your error.

Strange issue with an array

So I'm in the middle of working on a class called planner [no main in it as it's a separate class], but I'm having an issue with declaring an array with eclipse. You will need to enter it in eclipse to see what it is because I have no idea what it means by 'Syntax error on token ";", , expected'.
Here is the code:
import java.util.Scanner;
public class Planner {
private int maxEvents = 1000;
private int numEvents = 0;
private int choice;
int[] anArray;
anArray = new int [1000];
public void Planner() {
Scanner scan = new Scanner (System.in);
System.out.print("Press 1 to add an event. 2 to display events for the day. 3 to display events for the week. 4 to quit: ");
choice = scan.nextInt();
if (choice == 1){addEvent();}
if (choice == 2){displayOneDate();}
if (choice == 3){displayOneWeek();}
if (choice == 4){System.out.println("Have a good day.");}
else {Planner();}
}
public void addEvent() {
Event newEvent = new Event();
if (numEvents == maxEvents){System.out.println("Error: No more room.");}
else {
for (int i=0; anArray.length > i; i++) {
numEvents++;
newEvent.getEventFromUser();
}
}
}
public void displayOneDate() {
System.out.println("Event one: " + anArray[0]);
}
public void displayOneWeek() {
}
}
When you declare
int[] anArray;
anArray = new int [1000];
it should be
int[] anArray = new int [1000];
You cannot have executable code in class directly. You should have it either in method or constructor.
Otherwise if you want initialize the array you have to write like this int[] anArray = new int [1000];

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

Categories