IndexOutOfBoundsException when trying to get String from ArrayList - java

So I'm trying to create a small hangman mini-game. Unfortunately, I keep receiving the same error. I've attempted to re-do the game twice, but still can't seem to get it right. I'm sure it is simply some logic error or something.
I'm still relatively new to Java, so any help would be appreciated.
I've split the program into three classes. One for the Hangman object, one for the array containing said objects, and one for using the array of those objects. The three parts below are a snippet from the game.
Class 1: Hangman
package hangman2;
import java.util.*;
import java.io.*;
public class Hangman {
private ArrayList<String> words = new ArrayList<>();
private int diff;
public Hangman(String fileName, int difficulty) {
diff = difficulty;
//easy = 0; medium = 1; hard = 2
try {
Scanner scanFile = new Scanner(new File(fileName));
while(scanFile.hasNext()) {
String line = scanFile.nextLine();
Scanner scanLine = new Scanner(line);
String tempWord = scanLine.next();
words.add(tempWord);
}
}
catch (FileNotFoundException e) {
System.out.println("File not found\n" + e);
}
}
//Gets
public ArrayList<String> getWords() { return words; }
public int getDifficulty() { return diff; }
//Sets
public void addWord(String word) { words.add(word); }
}
Class 2: HangmanArray
package hangman2;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class HangmanArray {
private Hangman easyHangman;
private Hangman mediumHangman;
private Hangman hardHangman;
public HangmanArray() {
easyHangman = new Hangman("easy.txt", 0);
mediumHangman = new Hangman("medium.txt", 1);
hardHangman = new Hangman("hard.txt", 2);
}
public String getRandomWord() {
Hangman workingHangman = chooseDifficulty();
int max = workingHangman.getWords().size();
int randIndex = (int) (Math.random() * max);
return workingHangman.getWords().get(randIndex);
}
private Hangman chooseDifficulty() {
int chosenDifficulty = Integer.parseInt(JOptionPane.showInputDialog("Choose difficulty level\n"
+ "1: Novice\n2: Intermediate\n3: Expert"));
Hangman retHangman = null;
switch(chosenDifficulty) {
case 1: retHangman = easyHangman; break;
case 2: retHangman = mediumHangman; break;
case 3: retHangman = mediumHangman; break;
}
if (retHangman == null) {
System.out.println("Chosen difficulty not within range of [1;3]\nexiting");
System.exit(0);
}
return retHangman;
}
}
Class 3: HangmanUI
package hangman2;
public class HangmanUI {
public static void main(String[] args) {
HangmanArray hangmanArray = new HangmanArray();
System.out.println(hangmanArray.getRandomWord());
}
}
The error appears to be coming from line 25 of HangmanArray when difficulty 2 or 3 is selected:
return workingHangman.getWords().get(randIndex);
Any help is appreciated.

You should check whether max is 0 and, if so, return null or an empty string, then handle this special case.
I used Random.nextInt() instead of int randIndex = (int) (Math.random() * max);
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The general contract of nextInt is that one int value in the specified range is pseudorandomly generated and returned. All bound possible int values are produced with (approximately) equal probability
Keep in mind that the index of last element is size()-1
public String getRandomWord() {
Hangman workingHangman = chooseDifficulty();
int max = workingHangman.getWords().size();
if (max == 0) {
return "";
}
int randIndex = new Random().nextInt(max); // returns an integer between 0 and max-1
return workingHangman.getWords().get(randIndex);
}
You should also use try-with-resources to ensure that resources you're using are closed once you finisched with them.
public Hangman(String fileName, int difficulty) {
diff = difficulty;
//easy = 0; medium = 1; hard = 2
try (Scanner scanFile = new Scanner(new File(fileName))) {
while(scanFile.hasNext()) {
String line = scanFile.nextLine();
Scanner scanLine = new Scanner(line);
String tempWord = scanLine.next();
words.add(tempWord);
}
}
catch (FileNotFoundException e) {
System.out.println("File not found\n" + e);
}
}
Lastly I suggest to use the debugger in order to know what you're putting into every Hangman.

Related

How to print randomly generated letters using the random object into a 2D array

I'm trying to fill a 2D array with the reference variable called letters with randomly generated upper case letters using the Random object. I've tried doing it in both classes now but I still get a few errors that I've never encountered before. Any help on this is greatly appreciated.
Below are the errors I'm getting in the WordSearch class and where they are located:
I get an error that says, "char someChar = (char)(rand.nextInt(26) + 65);"
The error reads, "Syntax error on token ";", { expected after this token."
I'm also getting an error at the end of my for loop where the } is.
The error reads, "Syntax error, insert "}" to complete Block."
Lastly, I'm getting an error on the line that says, "public search(){"
The error reads, "Return type for the method is missing."
import java.util.Random;
import java.util.Scanner;
public class WordSearchTest {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int seed;
String word = " ";
String again = "y";
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a number from 1 - 9999:\n");
seed = keyboard.nextInt();
keyboard.nextLine(); //Consume the remaining new line
while(seed < 1 || seed > 9999) {
System.out.print("You must choose a number between 1 and 9999:\n");
seed = keyboard.nextInt();
keyboard.nextLine(); //Consume the remaining new line
}
while(again.equalsIgnoreCase("y")) {
System.out.print("Choose a word to search for:\n");
word = keyboard.nextLine();
System.out.print("Would you like to search for another word? (Y = Yes and N = No)\n");
again = keyboard.nextLine();
System.out.print(again);
while(!again.equals("Y") && !again.equals("y") && !again.equals("N") && !again.equals("n")) {
System.out.print("Invalid response. Y or N?\n");
again = keyboard.nextLine();
}
}
//Random rand = new Random(seed);
//char someChar = (char)(rand.nextInt(26) + 65);
//Instantiates a WordSearch object with reference variable puzzles and passes the arguments to the WordSearch constructor
WordSearch puzzles = new WordSearch(seed, word);
puzzles.search();
System.out.print("Terminating...");
System.exit(0);
}
}
import java.util.Random;
public class WordSearch {
private int seedNum;
private String wordGiven;
private int index = 0;
private char someCharz;
char[][] letters;
private char[][] lettersFound;
public WordSearch(int seeded, String wordUser) {
seedNum = seeded;
wordGiven = wordUser;
//someCharz = charz;
}
Random rand = new Random(seedNum);
char someChar = (char)(rand.nextInt(26) + 65);
letters = new char[4][4];
lettersFound = new char[4][4];
for(int col = 0; col < letters[0].length; col++)
{
for(int rowz = 0; rowz < letters.length; rowz++)
{
System.out.print(someCharz);
}
index++;
}
public search() {
System.out.print(letters);
}
/**
* #return the seedNum
*/
public int getSeedNum() {
return seedNum;
}
/**
* #param seedNum the seedNum to set
*/
public void setSeedNum(int seedNum) {
this.seedNum = seedNum;
}
/**
* #return the wordGiven
*/
public String getWordGiven() {
return wordGiven;
}
/**
* #param wordGiven the wordGiven to set
*/
public void setWordGiven(String wordGiven) {
this.wordGiven = wordGiven;
}
}
I am looking to see if I can find the cause of your first errors, but initially, the error about return type is easy; every method in Java must specify a return type. If the method returns nothing, and say--in this case--simply prints something to the console, the return type would be void.
Change the method declaration to public void search() {} and it will eliminate that error.

Issue converting array to array list

Trying to write a java code for a single row Battleship style game, and when I tried to convert from an array to an ArrayList, the game started returning "miss" no matter what.
public class SimpleDotComGame {
public static void main(String[] args) {
int numofGuess = 0;
Scanner sc = new Scanner(System.in);
SimpleDotCom dot = new SimpleDotCom();
int ranNum = (int) (Math.random() * 5);
ArrayList<Integer> locations = new ArrayList<Integer>();
locations.add(ranNum);
locations.add(ranNum + 1);
locations.add(ranNum + 2);
dot.setLocationCells(locations); //think like you're running a
// separate program with parameters to set cells as "locations"
boolean isAlive = true;
while (isAlive == true) {
System.out.println("Enter a number");
String userGuess = sc.next();
String result = dot.checkYourself(userGuess); //run program to
// check if cells were hit by userGuess
numofGuess++;
if (result.equals("kill")) {
isAlive = false;
System.out.println("You took " + numofGuess + " guesses");
}
}
sc.close();
}
}
public class SimpleDotCom {
int numofHits = 0;
ArrayList<Integer> locationCells;
public void setLocationCells(ArrayList<Integer> locations) { //locations
// variable described array so we must define it as array now
locationCells = locations;
}
public String checkYourself(String userGuess) { //check using parameter userGuess
int guess = Integer.parseInt(userGuess);
String result = "miss";
int index = locationCells.indexOf(userGuess);
if (index >= 0) {
locationCells.remove(index);
if (locationCells.isEmpty()) {
result = "kill";
} else {
result = "hit";
}
}
System.out.println(result);
return result;
}
}
Change :
int index = locationCells.indexOf(userGuess);
to
int index = locationCells.indexOf(guess);
userGuess is a String which can not possibly be in a list of Integers. guess is an int which can.

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.

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

Java sorting text file with Comparable

I need a program that reads in data and sorts the file in descending order using quicksort based on the index provided for instance this is the data using comparable
adviser,32/60,125,256,6000,256,16,128,198,199
amdahl,470v/7,29,8000,32000,32,8,32,269,253
amdahl,470v/7a,29,8000,32000,32,8,32,220,253
amdahl,470v/7b,29,8000,32000,32,8,32,172,253
amdahl,470v/7c,29,8000,16000,32,8,16,132,132
And i need to sort by the 5th index(mmax) case 2 and the 6th(cache) case 3 and the ninth index(php) case 4 in descending order & print the first index which is already sorted case 1
The problems with my code are as follows:
It doesn't sort based off the index
It gives me an error at runtime with the code: Arrays.sort(c);
Please help with suggestions
Thanks
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class Prog4 {
static Scanner input;
static File filename;
/**
* This function displays the menu for the user to choose an option from
*/
public void menu() {
System.out.println("Option 1: Sort by VENDOR: ");
System.out.println("Option 2: Sort decreasing number by MMAX: ");
System.out.println("Option 3: Sort decreasing number by CACH: ");
System.out.println("Option 4: Sort decreasing number by PRP: ");
System.out.println("Option 5: Quit program");
}
/**
* Constructor to handle the cases in the menu options
* #throws FileNotFoundException
* #throws IOException
*/
public Prog4() throws FileNotFoundException {
//Accepts user input
Scanner in = new Scanner(System.in);
//calls the menu method
menu();
//Initializes the run variable making the program loop until the user terminates the program
Boolean run = true;
//While loop
while (run) {
switch (in.nextInt()) {
case 1:
System.out.println("Option 1 selected");
System.out.println("Sorted by vendor:");
filename = new File("machine.txt");
//Instantiate Scanner s with f variable within parameters
//surround with try and catch to see whether the file was read or not
try {
input = new Scanner(filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Instantiate a new Array of String type
String array [] = new String[10];
//while it has next ..
while (input.hasNext()) {
//Initialize variable
int i = 0;
//store each word read in array and use variable to move across array array[i] = input.next();
//print
System.out.println(array[i]);
//so we increment so we can store in the next array index
i++;
}
case 2:
System.out.println("Press any key to continue");
Scanner input2 = new Scanner(System.in);
String x = input2.nextLine();
if (x.equals(0)) continue;
System.out.println("Option 2 selected") ;
Computer[] c = new Computer[10];
filename = new File("machine.txt");
try {
input = new Scanner(filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Arrays.sort(c);
while (input.hasNextLine()) {
for (int i = 0; i < c.length; i++) {
System.out.println(c[i]);
}
}
}
}
}
/**
* Main method
* #param args
* #throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
//Calls the constructor
new Prog4();
//static Scanner input;
}
public static void quickSort(int arr[], int left, int right) {
if (left < right) {
int q = partition(arr, left, right);
quickSort(arr, left, q);
quickSort(arr, q+1, right);
}
}
private static int partition(int arr[], int left, int right) {
int x = arr[left];
int i = left - 1;
int j = right + 1;
while (true) {
i++;
while (i < right && arr[i] < x)
i++;
j--;
while (j > left && arr[j] > x)
j--;
if (i < j)
swap(arr, i, j);
else
return j;
}
}
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
Comparator class:
import java.util.Comparator;
class Computer implements Comparable<Computer> {
private String vendor;
private int mmax;
private int cach;
private int php;
public Computer(int value) {
this.mmax = value;
}
public String getVendor() {
return vendor;
}
public void setVendor(String vendor) {
this.vendor = vendor;
}
public int getMmax() {
return mmax;
}
public void setMmax(int mmax) {
this.mmax = mmax;
}
public int getCach() {
return cach;
}
public void setCach(int cach) {
this.cach = cach;
}
public int getPhp() {
return php;
}
public void setPhp(int php){
this.php = php;
}
#Override
public int compareTo(Computer m) {
if (mmax < m.mmax) {
return -1;
}
if (mmax > m.mmax) {
return 1;
}
// only sort by height if age is equal
if (cach > m.cach) {
return -1;
}
if (cach < m.cach) {
return 1;
}
if (php > m.php) {
return -1;
}
if (php < m.php) {
return 1;
}
return 0;
}
public static Comparator<Computer> ComparemMax = new Comparator<Computer>() {
#Override
public int compare(Computer p1, Computer p2) {
return p2.getMmax() - p1.getMmax();
}
};
}
The biggest problem is that the Computer classes do not get instantiated for each line that gets read.
As you want to have different sort options depending on the user input, you can not let the Computer class determine the compare method, but instead you will need to create a separate Comparator implementation for each sort option. Next, make the file read operation generic and abstract it away in a separate method call from each selected case. Instead of an array of Computers, I would make it a List or a Set, because you don't (want to) know the length up front.
I would like to lay out the steps in detail so that you could figure out each step for yourself. You have got a lot of it right.. but there are gaps.
Create a Computer class. It should have a constructor which takes a single String and splits it using the separator ',' and parses each part to String/int as applicable. (It would be preferable for you to parse and store the whole string.. which means you can have 10 fields in your class)
Create a blank ArrayList to store the Computer objects.
Iterate through the file and readLine
Call the Computer constructor using the String representing each line in the file within the while loop
Add the new Computer object to the computers ArrayList
Write 5 different comparators.
Based on user input, instantiate the correct comparator and pass it to the sort method
Print the sorted array
If you still face a problem, mention the specific point at which you like more clarity..

Categories