I have a list of words (object) in an array. Each word has a number, word and hint. (please not the number is 1 more than the index it is in the array) I want the user to be able to delete an item in the array. I have written a method which reads the users input (int) the word, and hint in the index of the input takes the value of the hint and word in the next array and then that one will take the hint and word of the one after that etc. I have written the method but every time I delete a word any words after tat take the word and hint of the last object in the array
eg: first it’s like
1 dog bark
2 cat meow
3 cow moo
4 chicken cluck
5 pig oink
after the user deletes the word at 3
1 dog bark
2 cat meow
3 pig oink
4 pig oink
can anyone tell me what the problem is please?
code
public void deleteWord() throws IOException {
if (wCount > 0) {
int again = JOptionPane.YES_OPTION;
while (again == JOptionPane.YES_OPTION) {
int num = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter the number of the word you wish to delete", "Enter word number", JOptionPane.PLAIN_MESSAGE))-1;
int cnfrm = JOptionPane.showConfirmDialog(null, "Are you sure you wish to delete the word:" + "\n" + "\t" + wArr[num].getWrd(), "Are you sure?", JOptionPane.YES_NO_OPTION);
if (cnfrm == JOptionPane.YES_OPTION) {
for (int i = num; i < (wCount - 1); i++) {
for (int j = (i + 1); j < wCount; j++) {
wArr[i].setWrd(wArr[j].getWrd());
wArr[i].setHnt(wArr[j].getHnt());
}
}
wCount--;
wArr[wCount] = null;
}
PrintWriter pw = new PrintWriter(new FileWriter("words.txt", false));
for (int x = 0; x < wCount; x++) {
pw.println(wArr[x].toString(1));
}
pw.close();
displayWords();
again = JOptionPane.showConfirmDialog(null, "Do you wish to delete another word?", "Delete another wod?", JOptionPane.YES_NO_OPTION);
}
} else {
JOptionPane.showMessageDialog(null, "Thre are no words to delete", "ERROR", JOptionPane.ERROR_MESSAGE);
}
}
EDIT:
This is a homework assignment, which obviously means I still don’t know allot about programming, incl. ArrayLists. I will find out about them, but unfortunately this project (Hangman in case you were wondering) is due on Monday so I will not be implementing it in this program.
Your problem is this part:
In the end, it will always replace the content at position
iwith the one at positionwCount - 1.Use the following instead:
But as suggested in the comments to your question: Why not use a List (like ArrayList) instead?