How do I prevent a array resetting in tomcat? - java

I am working on a hangman project for school that is due tomorrow and I am using embedded tomcat in java. My program is currently able to accept an input from the servlet and and generate random word from a list that can remain constant while the page reloads. However every time I compare the letter input to the string (it is supposed to add the letter to a char array at the correct index location) it refreshes every time the page reloads so the word in the char array will never be complete- if that makes any sense :(
Here is the code:
private static String currentWord = gameWord();
private static final char[] untilEmpty = new char[currentWord.length()];
String temp = req.getParameter("Word");
if (temp == null) {
currentWord = gameWord();
} else {
currentWord = temp;
}
for (int i=0; i< currentWord.length();i++){
untilEmpty[i] = '_';
}
System.out.println(currentWord);
out.write("<form method=\"get\" action=\"game\" >".getBytes());
out.write("<p> Guess a letter:</p>".getBytes());
out.write("<input type=\"text\" name=\"Guess\">".getBytes());
out.write("<input type=\"submit\" value=\"enter here\">".getBytes());
out.write(String.format("<input type=\"text\" name=\"Word\" value=\"%s\">", currentWord).getBytes());
out.write("</form>".getBytes());
String letter = "";
boolean integer = false;
try {
letter = req.getParameter("Guess");
integer = validateString(letter, 0);
} catch (Exception e) {
}
//String untilEmpty = currentWord;
String subStr = "";
String Empty = currentWord;
if (integer == false) {
out.write("invalid input".getBytes());
} else {
//while (untilEmpty != "") {
char letterChar = letter.charAt(0);
if (currentWord.indexOf(letterChar) >= 0) {
int count = currentWord.length()- currentWord.replaceAll(letter,"").length();
System.out.println(count);
Empty = Empty.replaceAll(letter,"");
System.out.println(Empty);
for (int i =0; i<currentWord.length(); i++){
if (currentWord.charAt(i) == letter.charAt(0)){
untilEmpty[i]= letterChar;
//untilEmpty.indexOf(letter);
//untilEmpty[i] = untilEmpty+letter;
//untilEmpty = untilEmpty.substring(i)+letter.charAt(0);
}
}
System.out.println(untilEmpty);
} else {
System.out.println("incorrect guess");
}
}
System.out.println(letter);
if (Empty == "") {
System.out.println("guessed whole word :)");

I've never used embedded Tomcat but you could try to save state in the Session

Related

Append string after nth occurrence of a string

I have a string s to which I want to append another string s1 at the specified position.
String s = "17.4755,2.0585,23.6489,12.0045";
String s1=",,,,"
Now I want to add the string s1 after the n-th occurrence of "," character.
I have just started learning Java.
You can use the following method:
public String insert(int n, String original, String other) {
int index = original.indexOf(',');
while(--n > 0 && index != -1) {
index = original.indexOf(',', index + 1);
}
if(index == -1) {
return original;
} else {
return original.substring(0, index) + other + original.substring(index);
}
}
Working with Strings directly is not worth the trouble.
One easy way would be to turn your String into a List and manipulate that.
public void test() {
String s = "17.4755,2.0585,23.6489,12.0045";
// Split s into parts.
String[] parts = s.split(",");
// Convert it to a list so we can insert.
List<String> list = new ArrayList<>(Arrays.asList(parts));
// Inset 3 blank fields at position 2.
for (int i = 0; i < 3; i++) {
list.add(2,"");
}
// Create my new string.
String changed = list.stream().collect(Collectors.joining(","));
System.out.println(changed);
}
Prints:
17.4755,2.0585,,,,23.6489,12.0045
I think this is what you want
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = "17.4755,2.0585,23.6489,12.0045";
String s1=",,,,";
System.out.println("Enter Nth Occurrence");
try {
int n = scanner.nextInt();
long totalOccurrence = 0;
if (n != 0) {
totalOccurrence = s.chars().filter(num -> num == ',').count();
if (totalOccurrence < n) {
System.out.println("String s have only " + totalOccurrence + " symbol \",\"");
} else {
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ',') {
count++;
if (count == n) {
String resultString = s.substring(0, i) + s1 + s.substring(i, s.length());
System.out.println(resultString);
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Wrong input");
}
}
}
Output :
1. Enter Nth Occurrence
5
String s have only 3 symbol ","
2. Enter Nth Occurrence
2
17.4755,2.0585,,,,,23.6489,12.0045

Taking user input until <<EOF>> is entered

I'm going to start off by saying I already looked at the thread called "I have to make a loop taking users input until "done" is entered" I had no luck with the code answers that were given there.
The description I've been given for my edit command is this:
"Edits a text file if exists. Otherwise, creates new text file. The command waits for the user to type in text(must support multiple lines of text). The user ends the input by typing <<EOF>> and hitting enter."
Right now the code I have is this:
else if (spaceSplit[0].equals("edit")) {
String name = spaceSplit[1];
boolean endOfFile = false;
String content = "";
while(endOfFile == false){
String userInput = s.next();
content += userInput;
if(content.contains("<<EOF>>")){
endOfFile = true;
}
}
FileSystem.edit(name, content);
}
Nothing errors-out, but my else statement prints. My else statement code is this:
else {
System.out.println("That is not a command. Please try again.");
}
What is also funky is that the program goes through the whole do while loop then prints the else. I know this because what is exactly printed is: $That is not a commond. Please try again.
Here is the beginning of my do while loop:
do {
System.out.print("$");
String input = s.nextLine();
input = input.toLowerCase();
spaceSplit = input.split(" ");
Quite confusing. Also my edit(String name, String content) function is as follows:
public static void edit(String name, String content){
for(int i = 0; i < texts.size(); i++){
if(texts.get(i).getName().equals(name)){
texts.get(i).setContent(content);
} else {
texts.add(new TextFile(name,content));
for(int j = 0; j < directories.size(); j++){
if(directories.get(j).getName().equals(wDir.getName())){
texts.get(texts.size() - 1).setParent(directories.get(j));
System.out.println("The parent of " + name + " is " + directories.get(j).getName());
}
}
}
}
}
As you can see I've done a check at the end of my edit(name,content) method to check if the file is correctly created by printing out the parent directory of the text file.
This is how my program should function once I call the edit command:
$mkdir d
$cd d
$edit stuff.txt
Hello everyone, this is just an example!<<EOF>>
The parent of stuff.txt is d
$exit
Good Bye!
Any help provided would be greatly appreciated.
Here is the whole do while loop:
do {
System.out.print("$");
String input = s.nextLine();
input = input.toLowerCase();
spaceSplit = input.split(" ");
if (spaceSplit[0].equals("mkdir")) {
if (spaceSplit[1].equals("-p")) {
for (int i = 3; i < spaceSplit.length; i++) {
}
} else if (spaceSplit[1].contains("/")){
//This method will create a directory farther down the tree like creating c in a/b/c
String[] dirSplit = spaceSplit[1].split("/");
int length = dirSplit.length;
FileSystem.mkdir(dirSplit[length-1]);
int directoriesLength = FileSystem.directories.size();
for(int i = 0; i < FileSystem.directories.size(); i++){
if(dirSplit[length-2].equals(FileSystem.directories.get(i))){
FileSystem.directories.get(i).addChild(FileSystem.directories.get(directoriesLength-1));
//Checking if this works
System.out.println("The child was created succesfully");
}
}
} else {
for (int i = 1; i < spaceSplit.length; i++) {
FileSystem.mkdir(spaceSplit[i]);
}
}
} else if (spaceSplit[0].equals("cd")) {
FileSystem.cd(spaceSplit[1]);
} else if (spaceSplit[0].equals("pwd")) {
FileSystem.pwd();
} else if (spaceSplit[0].equals("ls")) {
} else if (spaceSplit[0].equals("edit")) {
String name = spaceSplit[1];
boolean endOfFile = false;
String content = "";
while(endOfFile == false){
String userInput = s.next();
content += userInput;
if(content.contains("<<EOF>>")){
endOfFile = true;
}
}
FileSystem.edit(name, content);
} else if (spaceSplit[0].equals("cat")) {
for(int i = 1; i < spaceSplit.length; i++){
FileSystem.cat(spaceSplit[i]);
}
} else if (spaceSplit[0].equals("updatedb")) {
} else if (spaceSplit[0].equals("locate")) {
} else if (spaceSplit[0].equals("exit")) {
exitProg = true;
System.out.println("Good bye!");
} else {
System.out.println("That is not a command. Please try again.");
}
} while (exitProg == false);
Alright, well I guess I'll answer my own question here. Everything works perfectly now.
else if (spaceSplit[0].equals("edit")) {
if(spaceSplit.length > 1) {
String name = spaceSplit[1];
boolean endOfFile = false;
String content = "";
while (!(content.contains("<<EOF>>"))) {
String userInput = s.nextLine();
content += userInput + " ";
}
String end = "<<EOF>>";
content = content.replace(end, "");
int size = tree.getTexts().size();
if (size != 0) {
for (int i = 0; i < size; i++) {
if (tree.getTexts().get(i).getName().equals(name)) {
tree.getTexts().get(i).setContent(content);
}
}
tree.edit(name, content);
} else {
tree.edit(name, content);
}
}
}

Reverse every 2nd word of a sentence

I am trying to reverse every 2nd words of every single sentence like
If a given string is :
My name is xyz
The desired output should be :
My eman is zyx
My current output is:
Ym eman s1 zyx
I am not able to achieve my desired output.Don't know what I am doing wrong here
Here is my code
char[] sentence = " Hi my name is person!".toCharArray();
System.out.println(ReverseSentence(sentence));
}
private static char[] ReverseSentence(char[] sentence)
{
//Given: "Hi my name is person!"
//produce: "iH ym eman si !nosrep"
if(sentence == null) return null;
if(sentence.length == 1) return sentence;
int startPosition=0;
int counter = 0;
int sentenceLength = sentence.length-1;
//Solution handles any amount of spaces before, between words etc...
while(counter <= sentenceLength)
{
if(sentence[counter] == ' ' && startPosition != -1 || sentenceLength == counter) //Have passed over a word so upon encountering a space or end of string reverse word
{
//swap from startPos to counter - 1
//set start position to -1 and increment counter
int begin = startPosition;
int end;
if(sentenceLength == counter)
{
end = counter;
}
else
end = counter -1;
char tmp;
//Reverse characters
while(end >= begin){
tmp = sentence[begin];
sentence[begin] = sentence[end];
sentence[end] = tmp;
end--; begin++;
}
startPosition = -1; //flag used to indicate we have no encountered a character of a string
}
else if(sentence[counter] !=' ' && startPosition == -1) //first time you encounter a letter in a word set the start position
{
startPosition = counter;
}
counter++;
}
return sentence;
}
If you want to reverse the alternate word you can try something like splitting the whole String into words delimited by whitespaces and apply StringBuilder reverse() on every second word like :-
String s = "My name is xyz";
String[] wordsArr = s.split(" "); // broke string into array delimited by " " whitespace
StringBuilder sb = new StringBuilder();
for(int i = 0 ; i< wordsArr.length; i++){ // loop over array length
if(i%2 == 0) // if 1st word, 3rd word, 5th word..and so on words
sb.append(wordsArr[i]); // add the word as it is
else sb.append(new StringBuilder(wordsArr[i]).reverse()); // else use StringBuilder revrese() to reverse it
sb.append(" ");// add a whitespace in between words
}
System.out.println(sb.toString().trim()); //remove extra whitespace from the end and convert StringBuilder to String
Output :- My eman is zyx
You can solve your problem vary easy way! Just use a flag variable which will indicate the even or odd position, more precisely whether any word will gonna be reversed or not!
Look at the following modification I made in your code, just added three extra line:
private static boolean flag = true;// added a variable flag to check if we reverse the word or not.
private static char[] ReverseSentence(char[] sentence)
{
//Given: "Hi my name is person!"
//produce: "iH ym eman si !nosrep"
if(sentence == null) return null;
if(sentence.length == 1) return sentence;
int startPosition=0;
int counter = 0;
int sentenceLength = sentence.length-1;
//Solution handles any amount of spaces before, between words etc...
while(counter <= sentenceLength)
{
if(sentence[counter] == ' ' && startPosition != -1 || sentenceLength == counter) //Have passed over a word so upon encountering a space or end of string reverse word
{
flag = !flag; // first time (odd position) we are not going to reverse!
//swap from startPos to counter - 1
//set start position to -1 and increment counter
int begin = startPosition;
int end;
if(sentenceLength == counter)
{
end = counter;
}
else
end = counter -1;
char tmp;
//Reverse characters
while(end >= begin & flag){ //lets see whether we are going to reverse or not
tmp = sentence[begin];
sentence[begin] = sentence[end];
sentence[end] = tmp;
end--; begin++;
}
startPosition = -1; //flag used to indicate we have no encountered a character of a string
}
else if(sentence[counter] !=' ' && startPosition == -1) //first time you encounter a letter in a word set the start position
{
startPosition = counter;
}
counter++;
}
return sentence;
}
Input
My name is xyz
Output:
My eman is zyx
The following code does this "special reverse" which reverses any other word in the sentence:
public static void main(String[] args) {
String sentence = "My name is xyz";
System.out.println(specialReverse(sentence)); // My eman is zyx
}
private static String specialReverse(String sentence) {
String result = "";
String[] words = sentence.split(" ");
// we'll reverse only every second word according to even/odd index
for (int i = 0; i < words.length; i++) {
if (i % 2 == 1) {
result += " " + reverse(words[i]);
} else {
result += " " + words[i];
}
}
return result;
}
// easiest way to reverse a string in Java in a "one-liner"
private static String reverse(String word) {
return new StringBuilder(word).reverse().toString();
}
Just for completeness here's Java-8 solution:
public static String reverseSentence(String input) {
String[] words = input.split(" ");
return IntStream.range(0, words.length)
.mapToObj( i -> i % 2 == 0 ? words[i] :
new StringBuilder(words[i]).reverse().toString())
.collect(Collectors.joining(" "));
}
reverseSentence("My name is xyz"); // -> My eman is zyx
package com.eg.str;
// Without using StringBuilder
// INPUT: "Java is very cool prog lang"
// OUTPUT: Java si very looc prog gnal
public class StrRev {
public void reverse(String str) {
String[] tokens = str.split(" ");
String result = "";
String k = "";
for(int i=0; i<tokens.length; i++) {
if(i%2 == 0)
System.out.print(" " + tokens[i] + " ");
else
result = tokens[i];
for (int j = result.length()-1; j >= 0; j--) {
k = "" + result.charAt(j);
System.out.print(k);
}
result = "";
}
}
public static void main(String[] args) {
StrRev obj = new StrRev();
obj.reverse("Java is very cool prog lang");
}
}
//reverse second word of sentence in java
public class ReverseSecondWord {
public static void main(String[] args) {
String s="hello how are you?";
String str[]=s.split(" ");
String rev="";
for(int i=0;i<str[1].length();i++)
{
char ch=str[1].charAt(i);
rev=ch+rev;
}
str[1]=rev;
for(int i=0;i<str.length;i++)
{
System.out.print(str[i]+" ");
}
}
}

counting unique words in a string without using an array

So my task is to write a program that counts the number of words and unique words in a given string that we get from the user without using arrays.
I can do the first task and was wondering how I could go about doing the second part.
For counting the number of words in the string I have
boolean increment = false;
for (int i = 0; i < inputPhrase.length(); i++){
if(validChar(inputPhrase.charAt(i))) //validChar(char c) is a simple method that returns a valid character{
increment = true;
}
else if(increment){
phraseWordCount ++;
increment = false;
}
}
if(increment) phraseWordCount++; //in the case the last word is a valid character
(originally i left this out and was off by one word)
to count unique words can I somehow modify this?
Here a suggestion how to do it without arrays:
1) Read every char until a blank is found and add this char to a second String.
2) If a blank is found, add it (or another token to seperate words) to the second String.
2a) Read every word from second String comparing it to the current word from he input String
public static void main(String[] args) {
final String input = "This is a sentence that is containing three times the word is";
final char token = '#';
String processedInput = "";
String currentWord = "";
int wordCount = 0;
int uniqueWordCount = 0;
for (char c : input.toCharArray()) {
if (c != ' ') {
processedInput += c;
currentWord += c;
} else {
processedInput += token;
wordCount++;
String existingWord = "";
int occurences = 0;
for (char c1 : processedInput.toCharArray()) {
if (c1 != token) {
existingWord += c1;
} else {
if (existingWord.equals(currentWord)) {
occurences++;
}
existingWord = "";
}
}
if (occurences <= 1) {
System.out.printf("New word: %s\n", currentWord);
uniqueWordCount++;
}
currentWord = "";
}
}
wordCount++;
System.out.printf("%d words total, %d unique\n", wordCount, uniqueWordCount);
}
Output
New word: This
New word: is
New word: a
New word: sentence
New word: that
New word: containing
New word: three
New word: times
New word: the
New word: word
12 words total, 10 unique
Using the Collections API you can count words with the following method:
private int countWords(final String text) {
Scanner scanner = new Scanner(text);
Set<String> uniqueWords = new HashSet<String>();
while (scanner.hasNext()) {
uniqueWords.add(scanner.next());
}
scanner.close();
return uniqueWords.size();
}
If it is possible that you get normal sentences with punctuation marks you can change the second line to:
Scanner scanner = new Scanner(text.replaceAll("[^0-9a-zA-Z\\s]", "").toLowerCase());
Every time a word ends findUpTo checks if the word is contained in the input before the start of that word. So "if if if" would count as one unique and three total words.
/**
* Created for http://stackoverflow.com/q/22981210/1266906
*/
public class UniqueWords {
public static void main(String[] args) {
String inputPhrase = "one two ones two three one";
countWords(inputPhrase);
}
private static void countWords(String inputPhrase) {
boolean increment = false;
int wordStart = -1;
int phraseWordCount = 0;
int uniqueWordCount = 0;
for (int i = 0; i < inputPhrase.length(); i++){
if(validChar(inputPhrase.charAt(i))) { //validChar(char c) is a simple method that returns a valid character{
increment = true;
if(wordStart == -1) {
wordStart = i;
}
} else if(increment) {
phraseWordCount++;
final String lastWord = inputPhrase.substring(wordStart, i);
boolean unique = findUpTo(lastWord, inputPhrase, wordStart);
if(unique) {
uniqueWordCount++;
}
increment = false;
wordStart = -1;
}
}
if(increment) {
phraseWordCount++; //in the case the last word is a valid character
final String lastWord = inputPhrase.substring(wordStart, inputPhrase.length());
boolean unique = findUpTo(lastWord, inputPhrase, wordStart);
if(unique) {
uniqueWordCount++;
}
}
System.out.println("Words: "+phraseWordCount);
System.out.println("Unique: "+uniqueWordCount);
}
private static boolean findUpTo(String needle, String haystack, int lastPos) {
boolean previousValid = false;
boolean unique = true;
for(int j = 0; unique && j < lastPos - needle.length(); j++) {
final boolean nextValid = validChar(haystack.charAt(j));
if(!previousValid && nextValid) {
// Word start
previousValid = true;
for (int k = 0; k < lastPos - j; k++) {
if(k == needle.length()) {
// We matched all characters. Only if the word isn't finished it is unique
unique = validChar(haystack.charAt(j+k));
break;
}
if (needle.charAt(k) != haystack.charAt(j+k)) {
break;
}
}
} else {
previousValid = nextValid;
}
}
return unique;
}
private static boolean validChar(char c) {
return Character.isAlphabetic(c);
}
}

Can't figure out what's triggering "java.util.ConcurrentModificationException"

My code is throwing an error that I've never seen before. So hey! I guess I'm learning ;) Anyway, I did some reading and generally this error is thrown when a list that is being iterated over is modified mid-iteration. However, I'm pretty sure I'm not modifying it. While the error is being thrown on partition(), if I don't assign a new value for currentList in updateCurrentList() (by commenting out the code), the program no longer throws the error. These two functions are called one after the other in my play() method, however the list iteration should be complete by the time the change is made. What am I missing? Do I have to close down the iterator somehow?
package hangman;
import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;
public class Hangman {
private Map<String, List<String>> wordPartitions; // groups words according to positions of guessed letter
private List<String> currentList; // remaining possible words that fit the information given so far
Set<Character> wrongGuesses; // holds all the "wrong" guesses so far
StringBuilder guessString; // current state of the word being guessed
String justHyphens; // for checking whether a guess was "wrong"
// initialize fields
// currentList should contain all (and only) words of length wordLength
// justHyphens and guessString should consist of wordLength hyphens
public Hangman(int wordLength) throws FileNotFoundException {
this.currentList = new ArrayList<String>();
addWords(wordLength);
wrongGuesses = new HashSet();
for(int i = 0; i < wordLength; i++) {
justHyphens += "-";
}
guessString = new StringBuilder();
wordPartitions = new HashMap();
}
private void addWords(int wordLength) throws FileNotFoundException {
Scanner words = new Scanner(new File("lexicon.txt"));
String word = "";
while(words.hasNext()) {
word = words.next();
if (word.length() == wordLength) {
currentList.add(word);
}
}
}
// main loop
public void play() {
char choice;
do {
choice = getUserChoice();
partition(choice);
updateCurrentList(choice);
} while (!gameOver());
endMessage();
}
// display the guessString and the missed guesses
// and get the next guess
private char getUserChoice() {
//generate a string from the incorrect choices char list
String wrong = "";
char letter;
if(!wrongGuesses.isEmpty()) {
Iterator<Character> letters = wrongGuesses.iterator();
letter = letters.next();
while(letters.hasNext()) {
letter = letters.next();
wrong += ", " + letter;
}
}
String letterStr = JOptionPane.showInputDialog("Incorrect choices: "+ wrong +"\n Tested letters: "+ guessString.toString() +"\nplease input a letter.");
return letterStr.charAt(0);
}
// use wordPartitions to partition currentList using
// keys returned by getPartitionKey()
private void partition(char choice) {
String word = "";
String key = "";
List<String> tempList = new ArrayList<String>();
Iterator<String> words = currentList.iterator();
//Generate a key for each word and add to appropriate arraylist within map.
while(words.hasNext()) {
word = words.next();
key = getPartitionKey(word, choice);
if(wordPartitions.containsKey(key)) {
tempList = wordPartitions.get(key);
tempList.add(word);
wordPartitions.put(key, tempList);
} else {
tempList.clear();
tempList.add(word);
wordPartitions.put(key, new ArrayList<String>());
}
}
}
// update currentList to be a copy of the longest partition
// if choice was "wrong", add choice to wrongGuesses
// if choice was "right", update guessString
private void updateCurrentList(char choice) {
String key = findLongestList();
currentList = wordPartitions.get(key);
if(key.equals(justHyphens)) {
wrongGuesses.add(choice);
} else {
addLetterToGuessString(guessString, choice, key);
}
}
private String findLongestList() {
Set<String> keySet = wordPartitions.keySet();
Iterator<String> keys = keySet.iterator();
String maxKey = "";
int maxKeyLength = 0;
List<String> tempList;
String tempKey = "";
while(keys.hasNext()) {
tempKey = keys.next();
tempList = wordPartitions.get(tempKey);
if(tempList.size() > maxKeyLength) {
maxKeyLength = tempList.size();
maxKey = tempKey;
}
}
return maxKey;
}
// checks for end of game
private boolean gameOver() {
return false;
}
// display the guessString and the missed guesses
// and print "Congratulations!"
private void endMessage() {
JOptionPane.showMessageDialog(null, "Congrats, yo!");
}
// returns string with '-' in place of each
// letter that is NOT the guessed letter
private String getPartitionKey(String s, char c) {
String word = "";
String letter = Character.toString(c);
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) == c) {
word += letter;
} else {
word += "-";
}
}
return word;
}
// update guessString with the guessed letter
private void addLetterToGuessString(StringBuilder guessString, char letter, String key) {
for(int i = 0; i < key.length(); i++) {
if(key.charAt(i) != '-') {
guessString.setCharAt(i, key.charAt(i));
}
}
}
}
The problem is that you are modifying a collection while you are iterating over it.
The collection is currentList, you are iterating over it in partition(). You modify it when you add a word to tempList here:
key = getPartitionKey(word, choice);
if(wordPartitions.containsKey(key)) {
tempList = wordPartitions.get(key);
tempList.add(word);
wordPartitions.put(key, tempList);
} else {
Why ? Because previously you called updateCurrentList() from play():
do {
choice = getUserChoice();
partition(choice);
updateCurrentList(choice);
} while (!gameOver());
And you updated currentList:
String key = findLongestList();
currentList = wordPartitions.get(key);
So, if the key returned by getPartitionKey(word, choice) is the same as the key previously returned by findLongestList(), currentListwill be the same as tempList, and so you will be modifying the collection you are iterating over.
The solution ? If tempList is the same as currentList, don't add the word to it (it already have the word, by definition). So, you can rewrite your if-else like that (I removed some useless code):
if(wordPartitions.containsKey(key)) {
tempList = wordPartitions.get(key);
} else {
wordPartitions.put(key, new ArrayList<String>());
}
if (tempList!=currentList) {
tempList.add(word);
}

Categories