I have a class Container where a user should be able to input any number of words until he types nothing. I have addWord(Word) method where each input is added to an ArrayList words every time do/while loop is run. I am passing user input value as a parameter to addWord() method each time loop runs.
Now I want to to display all elements of an array using display() method once the do/While loop has stopped running. But for some reason when i try to call method display(), it just shows an empty array [].
Is there any way you can help?
import java.util.ArrayList;
import java.util.List;
public class Container {
private List<String> words;
public Container() {
}
public List<String> getWords() {
return words;
}
public void setWords(List<String> words) {
this.words = words;
}
public void addWord(String word) {
words = new ArrayList<String>();
words.add(word);
}
public void display() {
System.out.println(words);
}
}
Main method:
import java.util.Scanner;
public class ContainerMain
{
public static void main(String[] args)
{
Container one = new Container();
Scanner myScan = new Scanner(System.in);
String word = "s";
do
{
word = myScan.nextLine();
one.addWord(word);
}
while (!word.equals(""));
if (word.equals("")) {
one.display();
}
else {
System.out.println("No hope fam");
}
}
}
Look at your addWord
method:
public void addWord(String word) {
words = new ArrayList<String>();
words.add(word);
}
Each time you call that, it's going to create a new list - so you can never end up with more than one word in it.
The first line, initializing words
, should be in your constructor (or as a field initializer). Then remove the line from addWord
- ideally making the words
field final at the same time, to avoid mistakes like this in the future, and remove the setWords
method unless you really need it for something else.
That's all that wrong in Container
(although it's not clear that it's really providing any value beyond just using a List<String>
directly). As noted in comments, currently your do/while loop in main
will add an empty string at the end. Also, there's no point in checking whether word
is empty or not after the loop - it has to be, otherwise you wouldn't have exited the loop!
See more on this question at Stackoverflow